Click here to Skip to main content
15,868,292 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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".
C#
 string myText = textBox1.Text;
 string searchWord = textBox2.Text;
 int counts = 0;
counts = Regex.Matches(myText , searchWord );
 MessageBox.Show(counts.ToString());
Posted
Updated 21-Oct-15 19:02pm
v3

try with Regex.Matches(myText, @"\b" + searchWord + @"\b")
 
Share this answer
 
Comments
VR Karthikeyan 22-Oct-15 1:23am    
Right answer...
DamithSL 22-Oct-15 1:39am    
Thank You
Shmuel Zang 22-Oct-15 1:35am    
5'ed.
DamithSL 22-Oct-15 1:39am    
Thank You
if you don't want to go with RegEx, you can use something like this:
C#
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;
}
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.
 
Share this answer
 
v2
Comments
Maciej Los 22-Oct-15 2:27am    
5ed!
Bill, you stole my answer :laugh:

Cheers, Maciej
;)
You can use like
C#
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();
 
Share this answer
 
Comments
ali mohammed1985 22-Oct-15 1:26am    
Thanks,,,
working fine.
Another way is to use Linq[^]:
C#
string s1 = @"Some text for testing. If God exists, then Haeven is open for you. If Devil exists, the Hell is open for you too.";
string searchedText = "for";


var result = s1.Split(' ').Where(a=>a.Contains(searchedText)).Count();

Console.WriteLine("'{0}' has found {1} time(s).", searchedText, result);


But, if you want to count occurencies for every word, try this:
C#
var words = s1.Split(new char[]{' ', ',', '.'}, StringSplitOptions.RemoveEmptyEntries)
        .GroupBy(a=>a)
        .Select(g=>new
            {
                Word = g.Key,
                Count = g.Count()
            })
        .OrderByDescending(b=>b.Count);

foreach(var word in words)
{
    Console.WriteLine("'{0}' has found {1} time(s).", word.Word, word.Count);
}

Note: i'm using defined chars-set to split string into words. You may be interested to add another chars, such as [;], [/], [?], etc.

Good luck!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900