原文:https://blog.youkuaiyun.com/raynaing/article/details/78240934
方法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() ? "无中文字符" : "有中文字符");
---------------------
作者:Uno2
来源:优快云
原文:https://blog.youkuaiyun.com/raynaing/article/details/78240934
版权声明:本文为博主原创文章,转载请附上博文链接!