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

Friends,

In this post, we will see how can we count the number of occurrences of a string within another string.

  1. public void CountOccurenceswWithinString()  
  2. {  
  3.    string test = "Hello, how are youyou you you you, you you yy?";  
  4.    int wordCount = 0;  
  5.    foreach (Match m in Regex.Matches(test, "you"))  
  6.    {  
  7.       wordCount++;  
  8.    }  
  9.    
  10.    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.

Rebin Infotech
Think. Innovate. Grow.