java判断字符串中是否含有中文

/**
     * 判断字符串中是否含有中文
     */
    public static boolean isCNChar(String s){
        boolean booleanValue = false;
        for(int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if(c > 128){
                booleanValue = true;
                break;
            }
        }
        return booleanValue;
    }

如果true,包含中文;

如果false,不包含中文

 

方式二、方式三,参考博客:https://www.cnblogs.com/fnlingnzb-learner/p/11512047.html

二、实现方式二        

1、利用正则表达式:

public static boolean isContainChinese(String str) {

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

2、优缺点:        

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

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

 

三、方式三    

1、改造正则

/**
     * 字符串是否包含中文
     *
     * @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;
    }

2、优缺点:

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

      b.缺点:目前尚未发现。

 

 

 

 

 

 

 

 

 

 

 

--

posted on 2018-03-13 22:18  有点懒惰的大青年  阅读(3263)  评论(0编辑  收藏  举报