最近看到网上还有人问怎么判断字符串中是否有连续两个中文?自己曾经也为字符串中有没有中文的问题苦恼过,正好这几天没事就整理一下网上的问题,做一个总结!
废话不多说了!看代码吧,写了一个工具类:主要考虑了三种情况,希望对大家的学习有帮助!
package duanqing.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 中文处理器,主要完成网上一些同志们的问到的问题,比如,判断字符串中是否有中文?
* 判断字符串中是否有连续几个中文?
* 判断字符串中有几个中文?
* @author 端端
*
*/
public class ChineseProcessor {
public static void main(String[] args) {
//System.out.println(isHasChinese("dsafsdf"));
//System.out.println(isHasContinuousChinese("ad是sfa是", 2));
System.out.println(getChineseCount("我是duanqing我怕谁"));
}
/**
* 是否包括中文
* @param content
* @return
*/
public static boolean isHasChinese(String content) {
String regEx = "[\u4e00-\u9fa5]";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(content);
while(matcher.find()) {
return true;
}
return false;
}
/**
* 是否含有连续的几个中文
* @param content 内容
* @param count 数量
* @return
*/
public static boolean isHasContinuousChinese(String content,int count) {
String regEx = "[\u4e00-\u9fa5]";
for(int i = 0; i < count - 1; i++) {
regEx += regEx;
}
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(content);
while(matcher.find()) {
return true;
}
return false;
}
/**
* 得到字符串里中文的数量
* @param content
* @return
*/
public static int getChineseCount(String content) {
int count = 0;
String regEx = "[\u4e00-\u9fa5]";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(content);
while(matcher.find()) {
count ++;
}
return count;
}
}