C# 程序,旨在统计字符串中某个词出现的次数
首先设置字符串 -
string str = "Hello World! Hello!";
现在,检查字符串中“Hello’单词出现的次数并遍历 -
while ((a = str1.IndexOf(pattern, a)) != -1) { a += pattern.Length; count++; }
示例
你可以尝试运行以下代码,来计算字符串中单词出现的次数。
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
广告