【问题标题】:What is a Surefire way to get a string Word Count in C#什么是在 C# 中获取字符串字数的 Surefire 方法
【发布时间】:2009-09-02 03:54:11
【问题描述】:

我不知道该怎么做。现在我正在计算空格以获取字符串的字数,但如果有双空格,则字数将不准确。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: c# regex text-parsing


    【解决方案1】:

    @Martin v. Löwis 的替代版本,它使用 foreach 和 char.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;
    }
    

    【讨论】:

    • “普通话”有多少个单词? (只是想一想)
    • @280Z28 - 你提出了一个好观点。仅供参考,甚至 MS Word 也将其视为 1 个单词。
    • “一二三;四”怎么样
    • @codeulike 是的另一个好点。由于这只是另一个海报答案的替代,更具文化意识的版本,我将保持原样。在一个真正的程序中,我会有单元测试来准确地表明我的预期。您可以说这更像是一种为自己解决答案的方法。如其他地方所述,其好处是它可以一次性运行并且内存压力最小。
    【解决方案2】:

    虽然基于 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;
      }
    

    效率更高(另外它还可以考虑额外的空白字符)。

    【讨论】:

    • 如果你要走那条路,我会建议一个 while 循环、一个索引变量和 string.IndexOfAny(char[], int)。
    • @bobbymcr 我看不出这有什么帮助。大概 IndexOfAny 只是线性搜索。
    • 在我的系统上,IndexOfAny 方法确实更快。线性扫描 + 开关 = 0.014 和 0.015 ms 之间;而 + IndexOfAny = 0.011 到 0.012 毫秒之间。此处代码:pastebin.ca/1551255 这无关紧要,但我想确定一下! :)
    • 哎呀,以前的代码中有一个错误...更正:pastebin.ca/1551268。性能结果是一样的。
    • @bobbymcr:我无法重现您的结果。案例版本运行 0.008 毫秒,索引版本 0.016 毫秒,使用 VS 2008。如果我使字符串更长(例如加倍 10 次),索引版本始终需要两倍的时间。
    【解决方案3】:

    这似乎对我有用:

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

    【讨论】:

    • 拆分会带来巨大的开销。通过字符循环将是最快的路径。 OTOH,RegEx 可能会比 Split 慢,因为结果数组的类型(字符串)比 Match 对象复杂。
    • 我在 Richard 的声明中调用了 Bullsh*t,结果证明 split 在某些情况下实际上更快,并且只比 foreach 解决方案慢一点。
    【解决方案4】:

    试试string.Split:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多