Java判断字符串长度
今天一个程序出了问题,排查了半天才发现,原来是因为原来的一个计算汉字长度的代码出了问题:
public static int getStringRealLength(String str) throws Exception{
String str1 = new String(str.getBytes("GB2312"),"iso-8859-1");
return str1.length();
}
汉字中有生僻字:“旸”,结果计算出长度为1。后来将GB2312改成GBK就可以了。因为字符可以正确算出长度。
原帖地址:https://blog.csdn.net/soundfuture/article/details/11601653
汉字所占byte问题请参考我的博文:https://blog.csdn.net/woshixuye/article/details/7907537
最后更新:2017-04-03 16:49:11