먼저 문자열을 선언합시다 -
string str = "Hello World!";
이제 전체 문자열을 반복하고 공백이나 탭 또는 개행 문자를 찾습니다. -
while (a <= str.Length - 1) {
if(str[a]==' ' || str[a]=='\n' || str[a]=='\t') {
myWord++;
}
a++;
} 예시
C#에서 문자열의 단어 수를 계산하는 전체 코드를 살펴보겠습니다.
using System;
public class Demo {
public static void Main() {
int a = 0 , myWord = 1;
string str = "Hello World!";
while (a <= str.Length - 1) {
if(str[a]==' ' || str[a]=='\n' || str[a]=='\t') {
myWord++;
}
a++;
}
Console.Write("Number of words in the string = {0}\n", myWord);
}
} 출력
Number of words in the string = 2