首先設定字串-
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中文網其他相關文章!