我被困在如何计算每个句子中有多少单词,一个例子是: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());
但我数不清每句话有多少个单词。