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
以上就是c# 程序计算字符串中某个单词的出现次数的详细内容。
