判断中文字符(包括中文汉字和中文符号)
(1)使用中文的编码区间来判断(推荐,效率高)
String str1 = "T恤;https://blog.csdn.net/vpqtxzmzezeqjj9977";//中文汉字 String str2 = ";https://blog.csdn.net/vpqtxzmzezeqjj9977";//中文分号 String str3 = "https://blog.csdn.net/vpqtxzmzezeqjj9977";//英文 int flage = 0; for (char c : str2.toCharArray()) { if (c >= 0x4E00 && c <= 0x9FA5){ flage = 1; System.out.println("发现中文字符:"+c); break; //有一个中文字符就返回 } } if(flage!=1){ System.out.println("恭喜,没有发现中文字符!"); }
相关学习视频推荐:java在线学习
(2)使用正则表达式来判断(不推荐,效率低,需要遍历整个字符串)
for (int i = 0; i < str1.length(); i++) { if (str.substring(i, i + 1).matches("[\\u4e00-\\u9fbb]+")) { flage = 1; System.out.println("发现中文字符:"+str.substring(i, i + 1)); break; //有一个中文字符就返回 } } if(flage!=1){ System.out.println("恭喜,没有发现中文字符!"); }
(3)使用Unicode编码来判断中文标点(推荐)
// GENERAL_PUNCTUATION 判断中文的“号 // CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号 // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号 private static final boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { return true; } return false; }
更多相关文章教程可以访问:java开发入门
The above is the detailed content of What are the methods to determine whether a string contains Chinese characters or characters in Java?. For more information, please follow other related articles on the PHP Chinese website!