How to find the first Chinese character in a java string example:
String str = "xing 杨某某";
How can i get the index of first Chinese character 杨 in above str. Thanks!
How to find the first Chinese character in a java string example:
String str = "xing 杨某某";
How can i get the index of first Chinese character 杨 in above str. Thanks!
This could help:
public static int firstChineseChar(String s) {
for (int i = 0; i < s.length(); ) {
int index = i;
int codepoint = s.codePointAt(i);
i += Character.charCount(codepoint);
if (Character.UnicodeScript.of(codepoint) == Character.UnicodeScript.HAN) {
return index;
}
}
return -1;
}
In your case, you have four ascii characters and then you have the other chinese character, so you can check, using a for loop, when a char is no more an ascii.
So, if char is different from ascii, then is, in this case I mean, a chinese character.
for(int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int char = (int) c;
if(char < 0 || char > 255) // Is not ascii
System.out.println("The first chinese char is: " + str.charAt(i);
}