本文介绍了在java中检测汉字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Java如何检测字符串是否包含汉字?
Using Java how to detect if a String contains Chinese characters?
String chineseStr = "已下架" ;
if (isChineseString(chineseStr)) {
System.out.println("The string contains Chinese characters");
}else{
System.out.println("The string contains Chinese characters");
}
你能帮我解决问题吗?
推荐答案
现在 Character.isIdeographic(int codepoint)
会告诉我们,代码点是CJKV ,日语,韩语和越南语)表意文字。
Now Character.isIdeographic(int codepoint)
would tell wether the codepoint is a CJKV (Chinese, Japanese, Korean and Vietnamese) ideograph.
更接近使用Character.UnicodeScript.HAN。
Nearer is using Character.UnicodeScript.HAN.
所以:
System.out.println(containsHanScript("xxx已下架xxx"));
public static boolean containsHanScript(String s) {
for (int i = 0; i < s.length(); ) {
int codepoint = s.codePointAt(i);
i += Character.charCount(codepoint);
if (Character.UnicodeScript.of(codepoint) == Character.UnicodeScript.HAN) {
return true;
}
}
return false;
}
或在java 8中:
public static boolean containsHanScript(String s) {
return s.codePoints().anyMatch(
codepoint ->
Character.UnicodeScript.of(codepoint) == Character.UnicodeScript.HAN);
}
这篇关于在java中检测汉字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!