计算字符串中单词的出现次数 [英] Counting of occurrences of a word in a string

查看:73
本文介绍了计算字符串中单词的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算一个字符串中确切的单词数。

我的代码给出了错误的结果,例如:

它计算之前这个词的时候我搜索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());

推荐答案

尝试使用 Regex.Matches(myText,@\ b+ searchWord + @\ b)


如果您不想使用RegEx,可以使用以下内容:
if you don't want to go with RegEx, you can use something like this:
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.


您可以使用喜欢

You can use like
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();


这篇关于计算字符串中单词的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆