在java来看,一个中文字符的长度也是1,但是将它转为byte[]数组后,一个中文字符则占两个字节。所以中文的个数则可以通过两者的差来计算。例子如下:
public class Alpha {
public static void main(String[] args) {
String str = "ada中大赛dsa";
int i = str.length();
byte[] bt = str.getBytes();
int j = bt.length;
int cnLen = j-i;
System.out.println("总共字符个数(1个中文也是1个):"+i);
System.out.println("中文字符个数:"+cnLen);
}
}
public class Alpha {
public static void main(String[] args) {
String str = "ada中大赛dsa";
int i = str.length();
byte[] bt = str.getBytes();
int j = bt.length;
int cnLen = j-i;
System.out.println("总共字符个数(1个中文也是1个):"+i);
System.out.println("中文字符个数:"+cnLen);
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货