First set the string -
string str = "Hello World! Hello!";
Now check if the word "Hello" appears in the string and loop-
while ((a = str1.IndexOf(pattern, a)) != -1) { a += pattern.Length; count++; }
You can try running the following code to count the occurrences of a word in a string.
Real-time demonstration
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; } }
Occurrence:2
The above is the detailed content of C# program to count the number of occurrences of a word in a string. For more information, please follow other related articles on the PHP Chinese website!