Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# นับจำนวนคำในสตริง

นับจำนวนคำในสตริงโดยนับตัวคั่น (space, newline, tab)

อัลกอริทึม

int wordCount = 1; // เริ่มที่ 1 เพราะคำแรกไม่มีตัวคั่นหน้า
for (int i = 0; i < str.Length; i++) {
    if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t') {
        wordCount++;
    }
}

ตัวอย่างโค้ดเต็ม

using System;
public class Demo {
    public static void Main() {
        int i = 0, wordCount = 1;
        string str = "Hello World!";
        while (i <= str.Length - 1) {
            if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t') {
                wordCount++;
            }
            i++;
        }
        Console.Write("Number of words in the string = {0}\n", wordCount);
    }
}

ผลลัพธ์

Number of words in the string = 2

ข้อจำกัด: ไม่นับคำที่มีช่องว่างซ้ำกัน (multiple spaces) ถูกต้อง

วิธีที่ดีกว่า (ใช้ Split):

int count = str.Split(new char[] {' ', '\n', '\t'}, StringSplitOptions.RemoveEmptyEntries).Length;