1、实用技巧Web篇(4)的Java实现
public static int getBytesLength(String s, String encode) {
if (s == null) {
return 0;
}
byte[] bytes;
if (encode == null) {
bytes = s.getBytes();
} else {
try {
bytes = s.getBytes(encode);
} catch (UnsupportedEncodingException e) {
bytes = s.getBytes();
}
}
return bytes.length;
}
public static String intercept(String s, int length, String encode) {
StringBuffer sb = new StringBuffer(s);
int len = getBytesLength(s, encode);
while (len > length) {
sb.deleteCharAt(sb.toString().length() - 1);
len = getBytesLength(sb.toString(), encode);
}
return sb.toString();
}
l Java中String对象提供了getBytes()方法将字符串转换成字节数组,可以通过其length属性获得字节数。
l 这里要注意的是全角字符的字节数通常是2;但一些特殊字符(例如①)的字节数到底是1还是2 ,由getBytes()时指定的字符编码决定,需要根据具体情况作调整。当不指定字符编码时,使用系统的字符编码。