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

转自:https://blog.csdn.net/zhanghan18333611647/article/details/80038629正则表达式

 

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

【前言】
       最近项目的短信服务对接外国的第三方发短信通道,第三方对短信内容有限制,不能含中文字符(若是含调用结果确定失败),因此在发送以前须要对短信内容作校验,看是否含有中文,若是含有则直接将短信发送状态改成失败,不用再去调用第三方;优化

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

1、实现方式一spa

一、针对每一个字符判断.net

 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     }

二、优缺点:        code

      a.缺点:效率低【每次都须要循环检测字符串中每一个字符】(每次发送都须要检测短信内容,每条内容有不少字符);blog

      b.优势:不只能检测出中文汉字还能检测中中文标点;教程

2、实现方式二        utf-8

一、利用正则表达式:

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     }

二、优缺点:        

        a.缺点:只能检测出中文汉字不能检测中文标点;

        b.优势:利用正则效率高;

3、方式三

一、改造正则

 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     }

二、优缺点:

      a.优势:效率既高又能检测出中文汉字和中文标点;

      b.缺点:目前还没有发现。

            

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

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