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

WBOY
Release: 2023-09-06 13:21:07
forward
1140 people have browsed it

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

First set the string -

string str = "Hello World! Hello!";
Copy after login

Now check if the word "Hello" appears in the string and loop-

while ((a = str1.IndexOf(pattern, a)) != -1) {
   a += pattern.Length;
   count++;
}
Copy after login

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;
   }
}
Copy after login

Output

Occurrence:2
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template