1.统计字符串的长度,中文占 2 个字符
/**
* 获取字符串的长度,如果有中文,则每个中文字符计为2位
* @param value 指定的字符串
* @return 字符串的长度
*/
public static int getStrLength(String value) {
int valueLength = 0;
String chinese = "[\u0391-\uFFE5]";
for (int i = 0; i < value.length(); i++) {
String temp = value.substring(i, i + 1);
if (temp.matches(chinese)) {
valueLength += 2;
} else {
valueLength += 1;
}
}
return valueLength;
}
2. 截取指定长度的字符串
/**
* 按字节长度截取字符串,中文占 2 个字符
* @param str 要截取的字符串
* @param subSLength 截取的长度
* @return
* @throws UnsupportedEncodingException
*/
public static String subStr(String str, int subSLength)
throws UnsupportedEncodingException {
if (str == null)
return "";
else{
int tempSubLength = subSLength;
String subStr = str.substring(0, str.length()<subSLength ? str.length() : subSLength);
int subStrByetsL = subStr.getBytes("GBK").length;
while (subStrByetsL > tempSubLength){
int subSLengthTemp = --subSLength;
subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp);
subStrByetsL = subStr.getBytes("GBK").length;
}
return subStr;
}
}