Java判斷字串是否包含中文以及包含的中文個數
阿新 • • 發佈:2019-02-10
import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternTest { public static void main(String[] args) { String str = "你好啊世界! hello world!/にほんご"; int chinaCount = 0; Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]"); int length = 0; if (str != null) { Matcher aMatcher = pattern.matcher(str); System.out.println("是否有中文:" + (aMatcher.find() ? "有" : "無")); char c[] = str.toCharArray(); length = c.length; for (int i = 0; i < length; i++) { Matcher matcher = pattern.matcher(String.valueOf(c[i])); if (matcher.matches()) { chinaCount++; } } } System.out.println("字串總個數:" + length); System.out.println("其中中文個數:" + chinaCount); System.out.println("非中文個數:" + (length - chinaCount)); } }