计算C#中的单词数

我正在尝试计算C#中富文本框中的单词数量,下面的代码只有在单行时才有效。 如何在不依赖正则表达式或任何其他特殊function的情况下执行此操作。

string whole_text = richTextBox1.Text; string trimmed_text = whole_text.Trim(); string[] split_text = trimmed_text.Split(' '); int space_count = 0; string new_text = ""; foreach(string av in split_text) { if (av == "") { space_count++; } else { new_text = new_text + av + ","; } } new_text = new_text.TrimEnd(','); split_text = new_text.Split(','); MessageBox.Show(split_text.Length.ToString ()); 

由于您只对单词计数感兴趣,并且您不关心单个单词,因此可以避免使用String.SplitString.Split很方便,但它不必要地生成(可能)大量的String对象,这反过来又给垃圾收集器带来了不必要的负担。 对于文本中的每个单词,需要实例化一个新的String对象,然后很快收集,因为您没有使用它。

对于家庭作业,这可能无关紧要,但如果您的文本框内容经常更改并且您在事件处理程序中进行此计算,则简单地手动迭代字符可能更明智。 如果你真的想使用String.Split ,那就选择像Yonix推荐的更简单的版本。

否则,请使用与此类似的算法:

 var text = richTextBox1.Text.Trim(); int wordCount = 0, index = 0; while (index < text.Length) { // check if current char is part of a word while (index < text.Length && !char.IsWhiteSpace(text[index])) index++; wordCount++; // skip whitespace until next word while (index < text.Length && char.IsWhiteSpace(text[index])) index++; } 

对于每个单词之间有多个空格的情况,此代码应该更好。

 char[] delimiters = new char[] {' ', '\r', '\n' }; whole_text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries).Length; 

有一些更好的方法可以做到这一点,但要与你所拥有的一致,请尝试以下方法:

 string whole_text = richTextBox1.Text; string trimmed_text = whole_text.Trim(); // new line split here string[] lines = trimmed_text.Split(Environment.NewLine.ToCharArray()); // don't need this here now... //string[] split_text = trimmed_text.Split(' '); int space_count = 0; string new_text = ""; 

现在制作两个foreach循环。 每行一个,一个用于计算行内的单词。

 foreach (string line in lines) { // Modify the inner foreach to do the split on ' ' here // instead of split_text foreach (string av in line.Split(' ')) { if (av == "") { space_count++; } else { new_text = new_text + av + ","; } } } new_text = new_text.TrimEnd(','); // use lines here instead of split_text lines = new_text.Split(','); MessageBox.Show(lines.Length.ToString()); } 

这是我刚刚采取的电话筛选面试问题(由位于加利福尼亚州的一家大公司出售各种以“i”字母开头的设备),我想我坦率地说…离线后,我写了这个。 我希望我能在访谈期间做到这一点。

 static void Main(string[] args) { Debug.Assert(CountWords("Hello world") == 2); Debug.Assert(CountWords(" Hello world") == 2); Debug.Assert(CountWords("Hello world ") == 2); Debug.Assert(CountWords("Hello world") == 2); } public static int CountWords(string test) { int count = 0; bool wasInWord = false; bool inWord = false; for (int i = 0; i < test.Length; i++) { if (inWord) { wasInWord = true; } if (Char.IsWhiteSpace(test[i])) { if (wasInWord) { count++; wasInWord = false; } inWord = false; } else { inWord = true; } } // Check to see if we got out with seeing a word if (wasInWord) { count++; } return count; } 

看看@Jay Riggs注释中提到的Lines属性,以及String.Split的这个重载使代码更简单。 然后最简单的方法是遍历Lines属性中的每一行,在其上调用String.Split ,并将它返回的数组的长度添加到运行计数中。

编辑:另外,你是否有任何理由使用RichTextBox而不是Multiline设置为True的TextBox?

你的方法是在正确的道路上。 我会做类似的事情,将richTextBox1的text属性传递给方法。 但是,如果您的富文本框格式化HTML,则这将不准确,因此您需要在运行单词计数之前去除任何HTML标记:

 public static int CountWords(string s) { int c = 0; for (int i = 1; i < s.Length; i++) { if (char.IsWhiteSpace(s[i - 1]) == true) { if (char.IsLetterOrDigit(s[i]) == true || char.IsPunctuation(s[i])) { c++; } } } if (s.Length > 2) { c++; } return c; } 

我们使用了Yoshi的答案的改编forms,在那里我们修复了如果在它后面没有空格的情况下它不会计算字符串中的最后一个字的错误:

 public static int CountWords(string test) { int count = 0; bool inWord = false; foreach (char t in test) { if (char.IsWhiteSpace(t)) { inWord = false; } else { if (!inWord) count++; inWord = true; } } return count; } 
 public static int WordCount(string str) { int num=0; bool wasInaWord=true;; if (string.IsNullOrEmpty(str)) { return num; } for (int i=0;i< str.Length;i++) { if (i!=0) { if (str[i]==' ' && str[i-1]!=' ') { num++; wasInaWord=false; } } if (str[i]!=' ') { wasInaWord=true; } } if (wasInaWord) { num++; } return num; } 

这应该工作

 input.Split(' ').ToList().Count; 

你也可以这样做!! 将此方法添加到扩展方法。

  public static int WordsCount(this string str) { return Regex.Matches(str, @"((\w+(\s?)))").Count; } 

并称之为这样。

  string someString = "Let me show how I do it!"; int wc = someString.WordsCount();