ให้เราประกาศสตริงก่อน -
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