>  기사  >  백엔드 개발  >  문자열에서 단어의 발생 횟수를 계산하는 C# 프로그램

문자열에서 단어의 발생 횟수를 계산하는 C# 프로그램

WBOY
WBOY앞으로
2023-09-06 13:21:07995검색

C# 程序计算字符串中某个单词的出现次数

먼저 문자열을 설정하세요. -

string str = "Hello World! Hello!";

이제 "Hello"라는 단어가 문자열에 나타나는지 확인하고 반복하세요. -

while ((a = str1.IndexOf(pattern, a)) != -1) {
   a += pattern.Length;
   count++;
}

Example

다음 코드를 실행하여 단어의 발생 횟수를 계산할 수 있습니다. 끈.

실시간 데모

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;
   }
}

Output

Occurrence:2

위 내용은 문자열에서 단어의 발생 횟수를 계산하는 C# 프로그램의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제