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推断字符串中是不是包含中文?的细致内容,更多请关注ki4网别的相干文章!