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

详细内容

9cada5f9dc100257cb69504f53714aef.png

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视频教程

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值