Click here to Skip to main content
14,827,034 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".
 string myText = textBox1.Text;
 string searchWord = textBox2.Text;
 int counts = 0;
counts = Regex.Matches(myText , searchWord );
Updated 21-Oct-15 19:02pm

try with Regex.Matches(myText, @"\b" + searchWord + @"\b")
VR Karthikeyan 22-Oct-15 1:23am
Right answer...
DamithSL 22-Oct-15 1:39am
Thank You
Shmuel Zang 22-Oct-15 1:35am
DamithSL 22-Oct-15 1:39am
Thank You
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;
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.
Maciej Los 22-Oct-15 2:27am
Bill, you stole my answer :laugh:

Cheers, Maciej
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();
ali mohammed1985 22-Oct-15 1:26am
working fine.
Another way is to use Linq[^]:
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:
var words = s1.Split(new char[]{' ', ',', '.'}, StringSplitOptions.RemoveEmptyEntries)
                Word = g.Key,
                Count = g.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!

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