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