Java to determine the number of Chinese in a string str, after summing up, there are several methods (all validated), according to its principles to determine under what circumstances to use which method:
1 char[] C = Str.tochararray ();
for (int i = 0; i < c.length i + +)
{
String len = integer.tobinarystring (C[i]);
if (Len.length () > 8)
Count + +;
}
Two bytes per Chinese, if the number of bytes in a character is greater than 8, it is judged as Chinese.
2 String regEx = "[\\u4e00-\\u9fa5]";
String term = str.replaceall (regEx, "AA");
Count = Term.length ()-str.length ();
[\u4e00-\u9fa5] is the Chinese Unicode encoding range, with the regular expression method, if there are characters in the string to meet the Chinese regular expression, it is judged as Chinese, replace it with two characters, so the length of the difference is the number of Chinese.
3 String regEx = "[\u4e00-\u9fa5]";
Pattern p = pattern.compile (regEx);
Matcher m = p.matcher (str);
while (M.find ())
{
Count + +;
}
As with the second method principle, just use the pattern class, if the Matcher can match, then found a Chinese character.
4 byte[] Bytstr = Str.getbytes ();
System.out.println (BYTSTR);
for (int i = 0; i < bytstr.length i + +)
{
if (Bytstr[i] < 0)//java Chinese characters are negative byte values
{
Count + +;
i++;//Chinese characters are double-byte
}
}
As the annotation above says, the Chinese character is a double byte, and the byte value of the Chinese character is negative, this method is used to judge.
5 String regEx = "[^\u4e00-\u9fa5]+";
string[] term = str.split (regEx);
for (int i =0 i < term.length i + +)
Count = Count + term[i].length ();
is still the method of judging regular expressions. The regular expression means the Unicode encoding of all the characters outside of the Chinese language, removing any characters other than the middle character, and the remainder is the Chinese character, which is the data of the string.
Conclusion: Regular expressions are very powerful.