[已解决]使用C#winForm VS2012计算每个句子中的单词 [英] [SOLVED]Counting words in each sentence using C# winForm VS2012
问题描述
大家好,
我需要创建一个程序,显示其中包含最多单词的句子。
我的3个句子是:
我喜欢苹果。我喜欢红苹果。我喜欢红苹果而不是青苹果。
如何显示包含最多单词的句子?
(结果应显示我喜欢红苹果而不是青苹果)
我是编程新手所以请理解我无法在这里发布我的代码因为我甚至不知道从哪里开始....
非常感谢提前〜
Hi all,
I need to create a program that shows a sentence with the most words in it.
My 3 sentences are:
I like apples. I like red apples. I like red apples than green apples.
How do I show a sentence with the most words in it?
(The result should be displaying "I like red apples than green apples")
I'm new to programming so please understand that I am not able to post my code here because I don't even know where to begin....
Thanks a lot in advance~
推荐答案
// requires Linq
private string testText = @"I like apples. I like red apples. I like red apples than green apples.";
private char[] sentenceDelimiter = new char[] {'.'};
// slower: sort, O(nlogn)
private string GetLongestSort(string sentences)
{
return
sentences.Split(sentenceDelimiter)
.OrderByDescending(s => s.Length).FirstOrDefault();
}
// much faster: aggregate, O(n)
private string GetLongestAggregate(string sentences)
{
return
sentences.Split(sentenceDelimiter)
.Aggregate("", (lenVar, itm) => lenVar.Length > itm.Length ? lenVar: itm);
}
// test ... inside a method or EventHandler
string longest1 = GetLongestSort(testText);
string longest2 = GetLongestAggregate(testText);
请尝试从这里得到一个想法,如果你想从这里得到输出,我会写一个示例代码。但在尝试使用此之前。
http://stackoverflow.com/questions/13485856/count-how-many-words-in-each-sentence [ ^ ]
Please try to get an idea from here, If you defecult to get output from here, I will write a sample code. But before try to find using this.
http://stackoverflow.com/questions/13485856/count-how-many-words-in-each-sentence[^]
请尝试以下代码:
Hi,
Please try the following code:
public int GetNoOfWords(string s)
{
return s.Split(new char[] { ' ', '.', ',','?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
上面的代码假设空格,逗号,句号,问号为单词分隔符,并返回单词计数。
并且像这样调用这个函数:
The above code assumes space, comma, full stop, question mark as word separators and will return the word count.
And call this function like this:
string text = "This is an simple example which demonstrates how to count the number words in a string using C#. This is a test string.Hence, Test it properly in c#.";
int words = GetNoOfWords(text)
查看位置你得到的数量是最大的。
希望这会有所帮助!!
问候,
Praneet
Check where you get the count to be maximum.
Hope this helps !!
Regards,
Praneet
这篇关于[已解决]使用C#winForm VS2012计算每个句子中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!