您好,欢迎访问一九零五行业门户网

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

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视频教程
以上就是java判断字符串中是否包含中文?的详细内容。
其它类似信息

推荐信息