问题描述
我需要计算一个字符串中确切的单词数。
我的代码给出了错误的结果,例如:
它计算之前这个词的时候我搜索for,因为之前这个词的部分类似于for。
I need to count the exact number of word in a string.
My code give me wrong result, for example:
It counts the word "before" when I search about "for" because part of the word "before" is similar to "for".
string myText = textBox1.Text;
string searchWord = textBox2.Text;
int counts = 0;
counts = Regex.Matches(myText , searchWord );
MessageBox.Show(counts.ToString());
推荐答案
using System.Linq; // required !
private char[] spaceandpunctuationdelimiters = new char[] {' ', '.', ',', '?', '!', ':', ';', '\t', '\r', '\n' };
private int GetTextMatchCount(bool ignorewhitespaceandpunctuation, bool ignorecase, string stringtosearch, string stringtofind)
{
// consider throwing an error here ?
if (string.IsNullOrEmpty(stringtosearch) || string.IsNullOrEmpty(stringtofind)) return 0;
if (ignorecase)
{
stringtosearch = stringtosearch.ToLowerInvariant();
stringtofind = stringtofind.ToLowerInvariant();
}
if (ignorewhitespaceandpunctuation)
{
string[] stringtonowhitespacestring;
stringtonowhitespacestring = stringtosearch.Split(spaceandpunctuationdelimiters, StringSplitOptions.RemoveEmptyEntries);
return stringtonowhitespacestring.Count(str => str == stringtofind);
}
// write the code to count matches for a string that includes white-space and/or punctuation here
// hint: you'll need to use 'IndexOf
return 0;
}
这里的代码示例反映了我的个人偏好:我宁愿编写程序代码而不是使用RegEx,因为我没有太多使用RegEx的经验;而且,我喜欢构建可以轻松维护/扩展的小代码工具的想法。
但是,我认识到RegEx是一个非常有价值的工具来掌握,并在需要时,打算深入研究。
您的里程可能会有所不同。
The code example here reflects my personal preferences: I'd rather write procedural code than use RegEx because I have not had much experience using RegEx; and, I like the idea of building small code "tools" that can be maintained/extended easily.
However, I recognize that RegEx is a very valuable tool to master, and, when the need arises, intend to study it in depth.
Your mileage may vary.
string myText = textBox1.Text;
string searchWord = textBox2.Text;
string[] source = myText.Split(' ');
var matchQuery = from word in source
where word.ToLowerInvariant() == searchWord.ToLowerInvariant()
select word;
int wordCount = matchQuery.Count();
这篇关于计算字符串中单词的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!