สมมติว่าเราต้องการนับจำนวนคำในสตริงต่อไปนี้ −
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