C# 字數統計(word count)

來源:互聯網
上載者:User

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不知道誰對誰錯

注意:連詞算一個不算兩個哦,那看來微軟吧連詞不算一個單詞

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.