Java检查字符串是否包含中文字符

转自:https://blog.csdn.net/zhanghan18333611647/article/details/80038629

 

强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan

【前言】
       最近项目的短信服务对接外国的第三方发短信通道,第三方对短信内容有限制,不能含中文字符(如果含调用结果肯定失败),所以在发送之前需要对短信内容做校验,看是否含有中文,如果含有则直接将短信发送状态改为失败,不用再去调用第三方;

【探索之旅】
       站在巨人的肩膀上, 立马在网上搜索一下关于Java怎么判断字符串中是否含有中文;果然网上有很多实现; 

一、实现方式一

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.缺点:目前尚未发现。

            

【总结】
        1、站在巨人的肩膀上,多去查,多做比较;

        2、针对程序不断的优化,比如第一种方式循环读字符串量大后很容易将服务器CPU搞崩。

posted @ 2019-09-12 15:14  Boblim  阅读(31634)  评论(0编辑  收藏  举报