문자열을 먼저 설정 -
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