有时我们需要截取字符串前面指定长度的字数,而一般情况JAVA的字符串的中文和英文符号都是按字符个数计数,比如“hello博客123”,这里如果使用String的.lenght方法获取的字符串长度是10位。而经常遇到的场景是按字节长度计算,即中文要算2位,英文数字符号算1位,所以示例的字符串字节长度应为12位。
以下是计算方法
public static String getStrCNmax(String str,int maxlen) {
int valueLength = 0;
String chinese = "[u0391-uFFE5]";
int n=0;
for (int i = 0; i < str.length(); i++) {
String temp = str. substring(i, i + 1);
if (temp.matches(chinese)) {
if(valueLength+2>maxlen){
break;
}
valueLength += 2;
} else {
if(valueLength+1>maxlen){
break;
}
valueLength += 1;
}
n=i;
}
return str.substring(0,n+1);
}



