我正在尝试从C#中的富文本框中计算单词的数量,下面的代码只有在单行时才有效.如何在不依赖正则表达式或任何其他特殊功能的情况下执行此操作.
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 ());
Run Code Online (Sandbox Code Playgroud)
Bed*_*sso 39
char[] delimiters = new char[] {' ', '\r', '\n' };
whole_text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries).Length;
Run Code Online (Sandbox Code Playgroud)
Gro*_*roo 24
由于您只对单词计数感兴趣,并且您不关心单个单词,String.Split
因此可以避免.String.Split
很方便,但它不必要地生成(可能)大量的String
对象,这反过来又给垃圾收集器带来了不必要的负担.对于文本中的每个单词,String
需要实例化一个新对象,然后很快收集,因为您没有使用它.
对于家庭作业,这可能无关紧要,但如果您的文本框内容经常更改并且您在事件处理程序中进行此计算,则简单地手动迭代字符可能更明智.如果你真的想使用String.Split
,那就选择像Yonix推荐的更简单的版本.
否则,请使用与此类似的算法:
int wordCount = 0, index = 0;
// skip whitespace until first word
while (index < text.Length && char.IsWhiteSpace(text[index]))
index++;
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++;
}
Run Code Online (Sandbox Code Playgroud)
对于每个单词之间有多个空格的情况,此代码应该更好.