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.
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