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

更新時間: 19-Jun-2020

3K+ 瀏覽量

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.