java 判斷字串是否包含漢字的方法
阿新 • • 發佈:2019-02-03
方法1:利用漢字的Unicode編碼範圍
public static void main(String[] args) throws UnsupportedEncodingException { int count = 0; String regEx = "[\\u4e00-\\u9fa5]"; String str = "中文fdas "; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); //p.matcher()只適合做 while (m.find()) { //m.matches()全部匹配為true //m.groupCount()用於獲取正則模式中子模式匹配的組,即只有正則中含有()分組的情況下才有用 for (int i = 0; i <= m.groupCount(); i++) { count++; } } System.out.println("共有 " + count + "個 "); }
方法2:根據漢字本身編碼為GBK和ASCII的長度區別
中文字元佔2個位元組,英文字元佔1個位元組
故:System.out.println(s.getBytes("GBK").length == s.length() ? "無中文字元" : "有中文字元");