Home  >  Article  >  Backend Development  >  C# program to count the number of occurrences of a word in a string

C# program to count the number of occurrences of a word in a string

WBOY
WBOYforward
2023-09-06 13:21:071136browse

C# 程序计算字符串中某个单词的出现次数

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++;
}

Example

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;
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete