C# 程式計算字串中某個單字的出現次數

WBOY
發布: 2023-09-06 13:21:07
轉載
1114 人瀏覽過

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
登入後複製

以上是C# 程式計算字串中某個單字的出現次數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!