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-6-2020

3K+次數瀏覽

開啟你的事業

完成課程獲得認證

開始
廣告
© . All rights reserved.