如何在 java 字符串中找到第一个汉字
How to find the first Chinese character in a java string
如何找到java字符串中的第一个汉字
示例:
String str = "xing 杨某某";
如何获取上面字符串中第一个汉字杨的索引?
谢谢!
这可能有帮助:
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;
}
在你的例子中,你有四个 ascii 字符,然后你有另一个汉字,所以你可以使用 for 循环检查一个字符何时不再是 ascii。
所以,如果 char 不同于 ascii,那么在这种情况下,我的意思是汉字。
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);
}
如何找到java字符串中的第一个汉字 示例:
String str = "xing 杨某某";
如何获取上面字符串中第一个汉字杨的索引? 谢谢!
这可能有帮助:
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;
}
在你的例子中,你有四个 ascii 字符,然后你有另一个汉字,所以你可以使用 for 循环检查一个字符何时不再是 ascii。
所以,如果 char 不同于 ascii,那么在这种情况下,我的意思是汉字。
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);
}