06/06/2015 by Nitesh

How To Count Occurrences of a String Within Another String in C#

Friends,

In programming while performing some business logic validations, many times we need to find a text within another text. In this post, we will see how can we count occurrences of a string within another string in C#.

static void CountOccurenceswWithinString()
{
   string test = "Hello, how are youyou you you you, you you yy?";
   int wordCount = 0;
   foreach (Match m in Regex.Matches(test, "you"))
   {
      wordCount++;
   }

   Console.WriteLine("Word count: {0}", wordCount);
}

In the above code snippet, we’re making use of Matches() of Regex class to get the number of matches of the word you in the string variable. Once we got this, we incremented the wordCount variable to know the total number of occurences of the string “you” in the entire string.

Hope you like this. Keep learning and sharing.

#.Net#C##Regex