常常會遇到字符串中有漢字和其他字符,當要判斷字符串是否爲漢字時就會涉及到Unicode,
String.getBytes().length取的是字節數,因爲中文是全角字符,所以每個中文的字節數都爲2
String.length()取的是字符長度,按中文的個數來截取。
具體java代碼如下:
String str = "中國chin受到腐蝕的 sfssfssdf ese";
for(int i=0;i<str.length();i++){
if(str.substring(i, i+1).matches("[/u4e00-/u9fa5]")){
System.out.println(str.subSequence(i, i+1)+"爲漢字。");
}else{
System.out.println(str.substring(i, i+1)+"不爲漢字");
}
}
[/u4e00-/u9fa5]是中文在Unicode中的編碼區間