Java判斷一個字符串str中中文的個數,經過總結,有以下幾種方法(全部經過驗證),可根據其原理判斷在何種情況下使用哪個方法:
1、
1 char[] c = str.toCharArray(); 2 for(int i = 0; i < c.length; i ++) 3 { 4 String len = Integer.toBinaryString(c[i]); 5 if(len.length() > 8) 6 count ++; 7 }
根據一個中文占兩個字節,假如一個字符的字節數大於8,則判斷為中文。
2 、
String regEx = "[\\u4e00-\\u9fa5]"; String term = str.replaceAll(regEx, "aa"); count = term.length()-str.length();
[\u4e00-\u9fa5]是中文的Unicode編碼范圍,用正則表達式的方法,若字符串中有字符滿足中文的正則表達式,則判定為中文,將其替換為兩個字符,故長度差就為中文的個數。
3、
String regEx = "[\u4e00-\u9fa5]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); while(m.find()) { count ++; }
與第二種方法原理一樣,只是用了Pattern類,若Matcher可以匹配,則說明找到了一個中文字符。
4、
byte[] bytStr = str.getBytes(); System.out.println(bytStr); for(int i = 0; i < bytStr.length; i ++) { if(bytStr[i] < 0 )//java中文字符是負的BYTE值 { count ++; i++;//中文字符是雙字節 } }
如上的注釋所說,中文字符是雙字節,且中文字符的byte值是負的,用這個方法來判斷。
5、
String regEx = "[^\u4e00-\u9fa5]+"; String[] term = str.split(regEx); for(int i =0; i < term.length; i ++) count = count + term[i].length();
仍然是正則表達式的判斷方法。該正則表達式的含義是出去中文以外的所有字符的Unicode編碼,將這些除去中文字符之外的其他字符去除,剩下的就都是中文字符,得到的就是中文字符串的數據。