Java 判断字符串中是否含有汉字
2016-09-02 · 做真实的自己 用良心做教育
千锋教育
千锋教育专注HTML5大前端、JavaEE、Python、人工智能、UI&UE、云计算、全栈软件测试、大数据、物联网+嵌入式、Unity游戏开发、网络安全、互联网营销、Go语言等培训教育。
向TA提问
关注
展开全部
Java判断字符串中是否包含汉字
Java代码
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IfHanZi {
public static void main(String[] args) {
//方法一:
String s1 = "我是中国人";
String s2 = "imchinese";
String s3 = "im中国人";
System.out.println(s1 + ":" + new String(s1).length());
System.out.println(s2 + ":" + new String(s2).length());
System.out.println(s3 + ":" + new String(s3).length());
System.out.println((s1.getBytes().length == s1.length()) ? "s1无汉字":"s1有汉字");
System.out.println((s2.getBytes().length == s2.length()) ? "s2无汉字":"s2有汉字");
System.out.println((s3.getBytes().length == s3.length()) ? "s3无汉字":"s3有汉字");
//方法二:
int count = 0;
String regEx = "[\\u4e00-\\u9fa5]";
String str = "中文fd我是中国人as ";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
count = count + 1;
}
}
System.out.println("共有 " + count + "个 ");
}
}
Java代码
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IfHanZi {
public static void main(String[] args) {
//方法一:
String s1 = "我是中国人";
String s2 = "imchinese";
String s3 = "im中国人";
System.out.println(s1 + ":" + new String(s1).length());
System.out.println(s2 + ":" + new String(s2).length());
System.out.println(s3 + ":" + new String(s3).length());
System.out.println((s1.getBytes().length == s1.length()) ? "s1无汉字":"s1有汉字");
System.out.println((s2.getBytes().length == s2.length()) ? "s2无汉字":"s2有汉字");
System.out.println((s3.getBytes().length == s3.length()) ? "s3无汉字":"s3有汉字");
//方法二:
int count = 0;
String regEx = "[\\u4e00-\\u9fa5]";
String str = "中文fd我是中国人as ";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
count = count + 1;
}
}
System.out.println("共有 " + count + "个 ");
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询