c#如何获取某个字符串中的含有多少个汉字?

济南云服务器 2024年7月1日08:27:16C#教程c#如何获取某个字符串中的含有多少个汉字?已关闭评论441阅读模式

在c#编程语言中,字符串可以包含很多种字符,比如,数字、汉字、字母等,如果,我们想要判断字符串中某一个内容是否是数字,可以使用char类型的IsDigit静态方法,同样,判断字符串中某一个字符是否是字母我们可以通过char类型的IsLetter静态来实现该需求,那么,如果要想获取某个字符串中汉字的总个数是多少?news.hcsw666.com/该如果实现呢?

方法一、

关键代码:

 

public int CountChineseCharacters(string input)
{
    int count = 0;
    foreach (char c in input)
    {
        if ((c >= '\u4E00' && c <= '\u9FA5') || char.IsSurrogatePair(c))
        {
            count++;
        }
    }
    return count;
}

方法二、

关键代码:

public int CountChineseCharactersWithRegex(string input)
{
    Regex regex = new Regex(@"[\u4E00-\u9FA5]");
    MatchCollection matches = regex.Matches(input);
    return matches.Count;
}

济南云服务器
  • 本文由 发表于 2024年7月1日08:27:16
  • 转载请务必保留本文链接:http://news.hcsw666.com/1345