
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!
Usage of delete statement
HTML space setting method
What should I do if the ps temporary disk is full?
How to restore mysql database
How to solve Java large file reading exception
Top 10 most secure digital currency exchanges in 2024
How to use the print function in python
How to set link style in css