Java判断字符串中是否包含汉字

Java判断字符串中是否包含汉字 

Java代码  收藏代码
    1. import java.util.regex.Matcher;  
    2. import java.util.regex.Pattern;  
    3.   
    4. public class IfHanZi {  
    5.    
    6.  public static void main(String[] args) {  
    7.   //方法一:  
    8.   
    9.   String s1 = "我是中国人";  
    10.   String s2 = "imchinese";  
    11.   String s3 = "im中国人";  
    12.   System.out.println(s1 + ":" + new String(s1).length());  
    13.   System.out.println(s2 + ":" + new String(s2).length());  
    14.   System.out.println(s3 + ":" + new String(s3).length());  
    15.   System.out.println((s1.getBytes().length == s1.length()) ? "s1无汉字":"s1有汉字");  
    16.   System.out.println((s2.getBytes().length == s2.length()) ? "s2无汉字":"s2有汉字");  
    17.   System.out.println((s3.getBytes().length == s3.length()) ? "s3无汉字":"s3有汉字");  
    18.   
    19.   //方法二:  
    20.   
    21.   int count = 0;  
    22.   String regEx = "[\\u4e00-\\u9fa5]";  
    23.   String str = "中文fd我是中国人as ";  
    24.   Pattern p = Pattern.compile(regEx);  
    25.   Matcher m = p.matcher(str);  
    26.   while (m.find()) {  
    27.      for (int i = 0; i <= m.groupCount(); i++) {  
    28.        count = count + 1;  
    29.      }  
    30.   }  
    31.   System.out.println("共有 " + count + "个 ");  
    32.  }  
    33. }  

posted on 2016-02-06 14:34  1130136248  阅读(714)  评论(0)    收藏  举报

导航