计算每个句子中的单词数量

我不知道如何计算每个句子中有多少单词,这个例子就是: string sentence = "hello how are you. I am good. that's good." 让它像:

 //sentence1: 4 words //sentence2: 3 words //sentence3: 2 words 

我可以得到句子的数量

  public int GetNoOfWords(string s) { return s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length; } label2.Text = (GetNoOfWords(sentance).ToString()); 

我可以得到整个字符串中的单词数

  public int CountWord (string text) { int count = 0; for (int i = 0; i < text.Length; i++) { if (text[i] != ' ') { if ((i + 1) == text.Length) { count++; } else { if(text[i + 1] == ' ') { count++; } } } } return count; } 

然后按钮1

  int words = CountWord(sentance); label4.Text = (words.ToString()); 

我无法计算每个句子中有多少单词。

为什么不使用Split呢?

  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()); 

而不是像在CountWords那样循环遍历字符串,我只会使用;

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

它更干净简单。 您在白色空格上拆分,返回所有单词的数组,该数组的长度是字符串中单词的数量。

如果你想要每个句子中的单词数量,你需要

 string s = "This is a sentence. Also this counts. This one is also a thing."; string[] sentences = s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); foreach(string sentence in sentences) { Console.WriteLine(sentence.Split(' ').Length + " words in sentence *" + sentence + "*"); } 

在s.Split返回的数组的每个元素上使用CountWord:

 string sentence = "hello how are you. I am good. that's good."; string[] words = sentence.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length; for (string sentence in sentences) { int noOfWordsInSentence = CountWord(sentence); } 
 string text = "hello how are you. I am good. that's good."; string[] sentences = s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); IEnumerable wordsPerSentence = sentences.Select(s => s.Trim().Split(' ').Length); 

正如在这里的几个答案中所提到的,看看像Split,Trim,Replace等字符串函数来让你前进。 这里的所有答案都将解决你的简单例子,但这里有一些句子可能无法正确分析;

 "Hello, how are you?" (no '.' to parse on) "That apple costs $1.50." (a '.' used as a decimal) "I like whitespace . " "Word" 

你的拼写是:

 int words = CountWord(sentance); 

和它有什么关系?