日期:2014-05-20 浏览次数:20843 次
/** * 返回指定字节长度的字符串 * * @param str String 字符串 * @param length int 指定长度 * @return String 返回的字符串 */ public static String toLength(String str, int length) { if (str == null) { return null; } if (length <= 0) { return ""; } try { if (str.getBytes("GBK").length <= length) { return str; } } catch (Exception ex) { } StringBuffer buff = new StringBuffer(); int index = 0; char c; length -= 3; while (length > 0) { c = str.charAt(index); if (c < 128) { length--; } else { length--; length--; } buff.append(c); index++; } buff.append("..."); return buff.toString(); }
------解决方案--------------------
你们说的长度是指 字节长度吧
但我不明白1楼的程序为什么要 length -= 3; 然后又 buff.append("...");
------解决方案--------------------
可以用正则表达式来判断输入字符是否是双字节字符,如果是双字节字符就+2,否则就+1
正则表达式是:
提取信息中的双字节字符串 (汉字):
[^\x00-\xff]*
------解决方案--------------------
public class Test { public static void main(String[] args) { String str2 = "abcdefghijklmnopq"; String str1 = "abcdefghijklmnop"; String str3 = "abcdefghijklmno"; String str4 = "一二三四五六七八九十一二三四五六"; String str5 = "一二三四五六七八"; String str6 = "一二三四五六七"; String str7 = "一二三a四五六七八九十一二三四五六"; String append = " ..."; System.out.println(trancate(str1, 16, append)); System.out.println(trancate(str2, 16, append)); System.out.println(trancate(str3, 16, append)); System.out.println(trancate(str4, 16, append)); System.out.println(trancate(str5, 16, append)); System.out.println(trancate(str6, 16, append)); System.out.println(trancate(str7, 16, append)); } private static String trancate(String src, int length) { return trancate(src, length, ""); } private static String trancate(String src, int length, String append) { int len = 0; char[] chars = src.toCharArray(); StringBuffer sb = new StringBuffer(); int i = 0; while(len < length) { if(i >= chars.length) { return sb.toString(); } sb.append(chars[i]); if(chars[i++] > 0xff) { len += 2; }else{ len++; } } if(sb.toString().equals(src)) { return sb.toString(); }else{ sb.append(append); return sb.toString(); } } }
------解决方案--------------------