字符串中的中文判断

这篇博客分享了如何使用Java进行中文字符判断,包括检查字符串中是否存在中文、是否包含连续的中文以及计算中文字符数量。通过正则表达式进行匹配,提供了`ChineseProcessor`工具类的三个方法:`isHasChinese`、`isHasContinuousChinese`和`getChineseCount`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看到网上还有人问怎么判断字符串中是否有连续两个中文?自己曾经也为字符串中有没有中文的问题苦恼过,正好这几天没事就整理一下网上的问题,做一个总结!

  废话不多说了!看代码吧,写了一个工具类:主要考虑了三种情况,希望对大家的学习有帮助!

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;
 }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值