Friday, February 13, 2009

java 计算字符串长度

/**
* 计算字符串长度,对于0-255之间的字符按1计算,大于255的字符按2计算
*
* @param str
* @return
*/
public static int getStringLength(String str) {
int length = 0;
Pattern pattern = Pattern.compile("([^\\x00-\\xff])");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
length++;
}
return str.length() + length;
}

No comments :