Back to Basic : How to count occurrences of a specific word in a sentence using C# ?

By | March 1, 2016

Write a C# code that count the occurrences of a word in a given sentence or string – yet another frequently  asked question in interview for the beginners. During the interview, while I found most of the developers were able to write the code, however the approaches taken are seems to  be lengthy. For an example, using substrings and split them it in array and then find the given string in array to match it.  Or by other way around with manipulating strings. Well, We can do it in much simpler way and lets try to understand it over here.

The Regex class is very much powerful and many times un-noticed which can perform task much faster and easily. Here is an quick example on how you can do it using Regex Class.

static void Main(string[] args)
        {
            string tobematched = "word";
            string sentence = "count the number of word in a string. count the number of word in a string. count the number of word in a string";
            int count = 0;
            foreach (Match match in Regex.Matches(sentence, tobematched,RegexOptions.ig))
            {
                count++;
            }

            Console.WriteLine("{0}" + " Found " + "{1}" + " Times", tobematched, count);
        }

Consider we have given sentence “ “count the number of word in a string. count the number of word in a string. count the number of word in a string” and we want to figure out the count of “word” in that given sentence.

Here is the output of the same.

image

Match class represents the results from a single regular expression match.  The Regex.Matches() method searches the specified input string for all occurrences of a specified regular and once it matched, it returns back to the Match class object.  Along with other details the Match object contains the values (the matched word) , and index of the found word, which you can use further.
image
Well, if you don’t like using foreach here, you can easily use the Count Directly with Matches method.

Regex.Matches(sentence, tobematched).Count

and you can print the details as follows:

Console.WriteLine("{0}" + " Found " + "{1}" + " Times", tobematched, Regex.Matches(sentence, tobematched).Count);

You can also use case sensitive match using RegexOptions.

image

 

on the other hand you can also use LINQ to find out the word occurrence very quickly and effectively. and here is a quick example.

Hope this helps !

2 thoughts on “Back to Basic : How to count occurrences of a specific word in a sentence using C# ?

  1. Pingback: Dew Drop – March 2, 2016 (#2200) | Morning Dew

  2. Pingback: Visual Studio – Developer Top Ten for Mar 4th, 2016 - Dmitry Lyalin

Comments are closed.