当前位置:首页 > C#教程 > C#进阶

C#计算字符串中单词的出现次数

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

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!