다음 문자열의 단어 수를 세고 싶다고 가정해 봅시다 -
str1 = "Hello World!";
이제 문자열 길이까지 루프를 돌고 아래와 같이 " ", \n, \t를 찾을 때 변수 개수를 증가시켜야 합니다. -
if(str1[a]==' ' || str1[a]=='\n' || str1[a]=='\t') {
count++;
} 다음 코드를 실행하여 C#에서 주어진 문자열의 단어 수를 계산할 수 있습니다.
예시
using System;
public class Demo {
public static void Main() {
string str1;
int a, count;
str1 = "Hello World!";
a = 0;
count = 1;
while (a <= str1.Length - 1) {
if(str1[a]==' ' || str1[a]=='\n' || str1[a]=='\t') {
count++;
}
a++;
}
Console.Write("Total words= {0}\n", count);
}
} 출력
Total words= 2