C# program to count occurrences of a word in string


Set the string first −

string str = "Hello World! Hello!";

Now check the string for the occurrences of a word “Hello’ and loop through −

while ((a = str1.IndexOf(pattern, a)) != -1) {
   a += pattern.Length;
   count++;
}

Example

You can try to run the following code to count occurrences of a word in a string.

Live Demo

using System;
class Program {
   static void Main() {
      string str = "Hello World! Hello!";
      Console.WriteLine("Occurrence:"+Check.CheckOccurrences(str, "Hello"));
   }
}
public static class Check {
   public static int CheckOccurrences(string str1, string pattern) {
      int count = 0;
      int a = 0;
      while ((a = str1.IndexOf(pattern, a)) != -1) {
         a += pattern.Length;
         count++;
      }
      return count;
   }
}

Output

Occurrence:2

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 19-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements