使用C#计算每个句子中的单词

我需要创建一个程序,显示其中包含最多单词的句子。

string [] st = { "I like apples.", "I like red apples.", "I like red apples than green apples." }; foreach (string s in st) { int NumberOfWords = s.Split(' ').Length; } 

结果应该显示“我喜欢红苹果而不是青苹果”。

可能在表单中有不同TextBox控件中的句子。 你知道哪个句子里面有更多的单词; 按空格分割句子并获得单词计数然后你可以比较。 类似下面的东西。

 int str1 = "I like apples".Split(' ').Length; int str2 = "I like red apples".Split(' ').Length; int str3 = "I like red apples than green apples".Split(' ').Length; 

这里split()函数返回一个字符串数组,因此你可以得到它的Length 。 现在您可以轻松地比较它们。

编辑:

下面是您发布的代码的完整示例代码。 将单词count存储在int[]数组中。 然后对数组进行排序。 显然,下面arr中的最后一个元素是具有最高单词的元素。

  static void Main(string[] args) { int[] arr = new int[3]; string[] st = { "I like apples.", "I like red apples.", "I like red apples than green apples." }; int counter = 0; foreach (string s in st) { int NumberOfWords = s.Split(' ').Length; arr[counter] = NumberOfWords; counter++; } Array.Sort(arr); Console.WriteLine(st[arr.Length - 1]); } 
 var result = st .OrderByDescending(s => s.Split(' ').Count()) .First(); 

这是使用Linq的快速单线程:

 return st.Select(s => s.Split(' ')).OrderByDescending(a => a.Length).First().Aggregate((s, next) => s + " " + next); 

所以基本上我们采取了4个单独的操作,并使用Linq将它们转换为一个语句。

  1. 将字符串数组转换为字符串数组的枚举,其中每个字符串现在是空格字符上自己的拆分数组。
  2. 按照每个数组的长度(字数)按降序排列数组(数组)(最大或最长,第一个)。
  3. 选择第一个数组(最长)。
  4. 将数组(您的原始字符串分成一个单词数组)并将其重新组合成一个字符串。

在课堂上,这可能看起来像:

 public string LongestString(params string[] args) { return args.Select(s => s.Split(' ')).OrderByDescending(a => a.Length).FirstOrDefault().Aggregate((s, next) => s + " " + next); } 

您需要通过包含“using System.Linq;”来确保包含Linq命名空间。 在文件的顶部(如果它还没有)。

如果您阅读其记录的摘要,您的代码非常好,那么您将看到s.Split()将返回包含指定字符的substring 。 但如果它是空的,那么你将获得单词的数量。 所以你可以用它作为:

 int NumberOfWords = s.Split().Length; 

请分享结果。

编辑:在你的循环声明一个整数之前

 int largest = 0; 

然后在你的循环中将代码写为

 int NumberOfWords = s.Split().Length; if(NumberOfWords > largest) { this.label1.Text = s; largest = NumberOfWords; } 

这样,您将在LabelText中获得包含大量单词的字符串

您可以使用Regex.Matches()来获取单词数,如下例所示:

 using System; using System.Text.RegularExpressions; class Program { static void Main() { const string t1 = "To be or not to be, that is the question."; Console.WriteLine(WordCounting.CountWords1(t1)); const string t2 = "Mary had a little lamb."; Console.WriteLine(WordCounting.CountWords1(t2)); } } ///  /// Contains methods for counting words. ///  public static class WordCounting { ///  /// Count words with Regex. ///  public static int CountWords1(string s) { MatchCollection collection = Regex.Matches(s, @"[\S]+"); return collection.Count; } }