Count how many words in each sentence

后端 未结 8 2052
耶瑟儿~
耶瑟儿~ 2021-01-17 05:55

I\'m stuck on how to count how many words are in each sentence, an example of this is: string sentence = \"hello how are you. I am good. that\'s good.\" and ha

8条回答
  •  天涯浪人
    2021-01-17 06:35

    If you only need a count, I'd avoid Split() -- it takes up unnecessary space. Perhaps:

    static int WordCount(string s)
    {
        int wordCount = 0;
        for(int i = 0; i < s.Length - 1; i++)
            if (Char.IsWhiteSpace(s[i]) && !Char.IsWhiteSpace(s[i + 1]) && i > 0)
                wordCount++;
        return ++wordCount;
    }
    
    public static void Main()
    {
        Console.WriteLine(WordCount(" H elloWor    ld g  ")); // prints "4"
    }
    

    It counts based on the number of spaces (1 space = 2 words). Consecutive spaces are ignored.

提交回复
热议问题