C# program to count occurrences of a word in string

CsharpServer Side ProgrammingProgramming

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
raja
Published on 24-Jul-2018 16:53:17
Advertisements