温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java如何判断字符串中是否有中文?

发布时间:2020-05-23 15:27:14 来源:亿速云 阅读:246 作者:鸽子 栏目:编程语言

java判断字符串中是否包含中文?

方法1、针对每个字符判断

public static boolean isChinese(String str) throws UnsupportedEncodingException
    {
        int len = str.length();
        for(int i = 0;i < len;i ++)
        {
            String temp = URLEncoder.encode(str.charAt(i) + "", "utf-8");
            if(temp.equals(str.charAt(i) + ""))
                continue;
            String[] codes = temp.split("%");
            //判断是中文还是字符(下面判断不精确,部分字符没有包括)
            for(String code:codes)
            {
                if(code.compareTo("40") > 0)
                    return true;
            }
        }
        return false;
    }

优缺点:

缺点:效率低【每次都需要循环检测字符串中每个字符】(每次发送都需要检测短信内容,每条内容有很多字符);

优点:不仅能检测出中文汉字还能检测中中文标点;

方法2、利用正则表达式

public static boolean isContainChinese(String str) {
 
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
}

优缺点:

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

优点:利用正则效率高;

方法3、改造正则

/**
  * 字符串是否包含中文
  *
  * @param str 待校验字符串
  * @return true 包含中文字符  false 不包含中文字符
  * @throws EmptyException
  */
 public static boolean isContainChinese(String str) throws EmptyException {
 
  if (StringUtils.isEmpty(str)) {
throw new EmptyException("sms context is empty!");
  }
  Pattern p = Pattern.compile("[\u4E00-\u9FA5|\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\“|\\”|\\?|\\:|\\;|\\【|\\】]");
  Matcher m = p.matcher(str);
  if (m.find()) {
return true;
  }
  return false;
 }

优缺点:

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

缺点:目前尚未发现。

以上就是java判断字符串中是否包含中文?的详细内容,更多请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI