C#计算字符串中的汉字个数

C#使用正则表达式计算字符串中的汉字个数。

///
/// 计算字符串中的汉字个数
///
///字符串
/// 汉字个数
public static int getHanZiCount(string str)
{
    Regex r = new Regex("^[\u4E00-\u9FA5]{0,}$");
    int count = 0; // 汉字个数
    for (int i = 0; i < str.Length; i++)
    {
        if (r.IsMatch(str[i].ToString()))
        {
            count++;
        }
    }
    return count;
}

猜你喜欢

转载自www.cnblogs.com/alpha-w/p/10806299.html