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

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

การนับจำนวนคำในสตริง ทำได้โดยการนับตัวคั่นคำ เช่น Space ( ), Tab (\t), Newline (\n) แล้วบวก 1 (เพราะคำสุดท้ายไม่มีตัวคั่นท้าย)

อัลกอริทึม

  1. ตั้งค่า Count = 1 (คำแรก)
  2. วนลูปตรวจสอบทุกตัวอักษรในสตริง
  3. หากเจอ Space, Tab, Newline ให้ Count++
  4. ผลลัพธ์ = จำนวนคำ

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

using System;

public class Demo
{
    public static void Main()
    {
        string str1 = "Hello World!";
        int count = 1; // เริ่มจาก 1 (คำแรก)
        
        for (int a = 0; a < str1.Length; a++)
        {
            if (str1[a] == ' ' || str1[a] == '\n' || str1[a] == '\t')
            {
                count++;
            }
        }
        
        Console.WriteLine($"Total words = {count}");
    }
}

ผลลัพธ์

Total words = 2

วิธีที่ดีกว่า (Best Practice)

ใช้ String.Split หรือ Regex จัดการหลาย Space, Tab, Newline ได้ดีกว่า:

วิธี Split (ง่าย)

string text = "Hello   World!\nNew\tLine";
string[] words = text.Split(new char[] { ' ', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(words.Length); // 4

วิธี Regex (ทรงพลัง)

using System.Text.RegularExpressions;

string text = "Hello   World!\nNew\tLine";
int count = Regex.Matches(text, @"\S+").Count; // \S+ = non-whitespace sequence
Console.WriteLine(count); // 4

ข้อควรระวัง

  • หลาย Space ติดกัน - วิธีลูปธรรมดาจะนับผิด
  • Space นำหน้า/ท้ายสตริง - ต้อง Trim ก่อน
  • Unicode Whitespace - มีมากกว่า Space/Tab/Newline

สรุป: โค้ดตัวอย่างเป็นพื้นฐาน สำหรับ Production ควรใช้ Split หรือ Regex