簡體   English   中英

Surefire在C#中獲取字符串字數統計的方法是什么

[英]What is a Surefire way to get a string Word Count in C#

我不確定該怎么做。 現在,我正在計算空格以獲取字符串的字數,但是如果存在雙倍空格,則字數將不准確。 有一個更好的方法嗎?

@Martin v。Löwis的替代版本,它使用foreachchar.IsWhiteSpace() ,在處理其他文化時應該更正確。

int CountWithForeach(string para)
{
    bool inWord = false;
    int words = 0;
    foreach (char c in para)
    {
        if (char.IsWhiteSpace(c))
        {
            if( inWord )
                words++;
            inWord = false;
            continue;
        }
        inWord = true;
    }
    if( inWord )
        words++;

    return words;
}

盡管基於Split的解決方案很難編寫,但它們可能會變得昂貴,因為所有的字符串對象都需要創建然后丟棄。 我希望有一個明確的算法,例如

  static int CountWords(string s)
  {
    int words = 0;
    bool inword = false;
    for(int i=0; i < s.Length; i++) {
      switch(s[i]) {
      case ' ':case '\t':case '\r':case '\n':
          if(inword)words++;
          inword = false;
          break;
      default:
          inword = true;
          break;
      }
    }
    if(inword)words++;
    return words;
  }

效率更高(此外,它還可以考慮其他空格字符)。

這似乎為我工作:

var input = "This is a  test";
var count = input.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length;

嘗試string.Split

string sentence = "This     is a sentence     with  some spaces.";
string[] words = sentence.Split(new char[] { ' ' },  StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM