您的位置:首页 > 编程语言 > Java开发

java 判断字符串是否包含汉字的方法

2017-10-15 15:11 423 查看
方法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() ? "无中文字符" : "有中文字符");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: