Count how many words in each sentence

后端 未结 8 2040
耶瑟儿~
耶瑟儿~ 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:36

    Why not use Split instead?

            var sentences = "hello how are you. I am good. that's good.";
    
            foreach (var sentence in sentences.TrimEnd('.').Split('.'))
                Console.WriteLine(sentence.Trim().Split(' ').Count());
    
    0 讨论(0)
  • 2021-01-17 06:37

    Instead of looping over the string as you do in CountWords I would just use;

     int words = s.Split(' ').Length;
    

    It's much more clean and simple. You split on white spaces which returns an array of all the words, the length of that array is the number of words in the string.

    0 讨论(0)
提交回复
热议问题