C# 字数统计(word count)

1、Regex.Matches(s, @"[A-Za-z0-9][A-Za-z0-9'\-.]*").Count (英文单词连词算一个单词)

Regex.Matches(s, @"[A-Za-z0-9][A-Za-z0-9\-.]*").Count (英文单词连词不算一个单词)

2、           string[] str=FilterHtml(content).Split("~!@#$%^&*()_+-=`|\\:\"?><;',./ ".ToCharArray());

                int i=0;

                foreach (string s in str)

                {

                    if (s.Length == 0)

                        i++;

                }

                count = str.Length - i;

其中第2种方法的缺点不能统计数字字数 比如123.456他会当两个单词,以上方法只适用英文字数统计

3、Regex.Matches(txtContent.Text, @"[\W]+").Count 中文字数

Regex.Matches(strContent, @"[0-9][0-9'\-.]*").Count 数字字数

中文字数统计:

    public static int ChineseLetterCount(string strText)
    {
        byte[] byts = System.Text.Encoding.GetEncoding("gb2312").GetBytes(strText);
 

        return byts.Length - strText.Length;

    }

以上都是近似统计

 英文字数统计已经很精确了,中文字数统计误差有点大,还有待改进

不过我在做对比测试的发现word2010统计有一点bug:

请看以下测试用例:

"I looked at it and said, 'We'll be back in a few days,' " Byron Largent said of the china. (word2010里面字数统计为20)

而我写的正则统计为19不知道谁对谁错

注意:连词算一个不算两个哦,那看来微软吧连词不算一个单词

 
原文地址:https://www.cnblogs.com/tewuapple/p/2570893.html