Word Count Algorithm in C#

前端 未结 7 1465
天涯浪人
天涯浪人 2021-01-05 02:37

I am looking for a good word count class or function. When I copy and paste something from the internet and compare it with my custom word count algorithm and MS Word it is

7条回答
  •  时光说笑
    2021-01-05 03:23

    I've just had the same problem in ClipFlair, where I needed to calculate WPM (Words-per-minute) for Movie Captions, so I came up with the following one:

    You can define this static extension method in a static class and then add a using clause to the namespace of that static class at any class that needs to use this extension method. The extension method is invoked using s.WordCount(), where s is a string (an identifier [variable/constant] or literal)

    public static int WordCount(this string s)
    {
      int last = s.Length-1;
    
      int count = 0;
      for (int i = 0; i <= last; i++)
      {
        if ( char.IsLetterOrDigit(s[i]) &&
             ((i==last) || char.IsWhiteSpace(s[i+1]) || char.IsPunctuation(s[i+1])) )
          count++;
      }
      return count;
    }
    

提交回复
热议问题