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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP