Java检查字符串是否包含中文字符
转自:https://blog.csdn.net/zhanghan18333611647/article/details/80038629 ? 强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan 【前言】 【探索之旅】 一、实现方式一 1、针对每个字符判断 1 public static boolean isChinese(String str) throws UnsupportedEncodingException 2 { 3 int len = str.length(); 4 for(int i = 0;i < len;i ++) 5 { 6 String temp = URLEncoder.encode(str.charAt(i) + "","utf-8"); 7 if(temp.equals(str.charAt(i) + "")) 8 continue; 9 String[] codes = temp.split("%"); 10 //判断是中文还是字符(下面判断不精确,部分字符没有包括) 11 for(String code:codes) 12 { 13 if(code.compareTo("40") > 0) 14 return true; 15 } 16 } 17 return false; 18 } 2、优缺点:? ? ? ?? ? ? ? a.缺点:效率低【每次都需要循环检测字符串中每个字符】(每次发送都需要检测短信内容,每条内容有很多字符); ? ? ? b.优点:不仅能检测出中文汉字还能检测中中文标点; 二、实现方式二? ? ? ?? 1、利用正则表达式: 1 public static boolean isContainChinese(String str) { 2 3 Pattern p = Pattern.compile("[u4e00-u9fa5]"); 4 Matcher m = p.matcher(str); 5 if (m.find()) { 6 return true; 7 } 8 return false; 9 } 2、优缺点:? ? ? ?? ? ? ? ? a.缺点:只能检测出中文汉字不能检测中文标点; ? ? ? ? b.优点:利用正则效率高; 三、方式三 1、改造正则 1 /** 2 * 字符串是否包含中文 3 * 4 * @param str 待校验字符串 5 * @return true 包含中文字符 false 不包含中文字符 6 * @throws EmptyException 7 */ 8 public static boolean isContainChinese(String str) throws EmptyException { 9 10 if (StringUtils.isEmpty(str)) { 11 throw new EmptyException("sms context is empty!"); 12 } 13 Pattern p = Pattern.compile("[u4E00-u9FA5|!|,|。|(|)|《|》|“|”|?|:|;|【|】]"); 14 Matcher m = p.matcher(str); 15 if (m.find()) { 16 return true; 17 } 18 return false; 19 } 2、优缺点: ? ? ? a.优点:效率既高又能检测出中文汉字和中文标点; ? ? ? b.缺点:目前尚未发现。 ? ? ? ? ? ?? 【总结】 ? ? ? ? 2、针对程序不断的优化,比如第一种方式循环读字符串量大后很容易将服务器CPU搞崩。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |