• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

java 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

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|<span style="color:transparent">本文来源gaodai#ma#com搞*!代#%^码网%</span>\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\“|\\”|\\?|\\:|\\;|\\【|\\】]");  Matcher m = p.matcher(str);  if (m.find()) {return true;  }  return false; }

优缺点:

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

缺点:目前尚未发现。

推荐学习:Java视频教程

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:java判断字符串中是否包含中文?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址