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

โปรแกรม Java นับตัวอักษรในแต่ละคำของประโยค

โจทย์: แยกคำ (words) แล้วนับตัวอักษรในแต่ละคำ

ตัวอย่างโค้ด (ปรับปรุง: ใช้ Split + Map)


import java.util.*;

public class Demo {
    public static void countCharsPerWord(String sentence) {
        if (sentence == null || sentence.trim().isEmpty()) return;
        
        // Split by whitespace (1 or more)
        String[] words = sentence.trim().split("\\s+");
        
        for (String word : words) {
            // นับตัวอักษรในคำนี้ (ignore punctuation ถ้าต้องการ)
            String cleanWord = word.replaceAll("\\p{Punct}", "");
            System.out.println("Word: \"" + word + "\" → Length: " + cleanWord.length() + " chars");
            
            // นับแต่ละตัวอักษรในคำ (optional)
            Map charCount = new LinkedHashMap<>();
            for (char c : cleanWord.toCharArray()) {
                charCount.merge(c, 1, Integer::sum);
            }
            System.out.println("  Char breakdown: " + charCount);
        }
    }
    
    public static void main(String[] args) {
        String sentence = "This is a sample sentence!";
        countCharsPerWord(sentence);
    }
}

ผลลัพธ์

Word: "This" → Length: 4 chars
  Char breakdown: {T=1, h=1, i=1, s=1}
Word: "is" → Length: 2 chars
  Char breakdown: {i=1, s=1}
Word: "a" → Length: 1 chars
  Char breakdown: {a=1}
Word: "sample" → Length: 6 chars
  Char breakdown: {s=1, a=1, m=1, p=1, l=1, e=1}
Word: "sentence!" → Length: 8 chars
  Char breakdown: {s=1, e=3, n=1, t=1, c=1}

วิธีเดิมในโจทย์ (นับรวมทั้งประโยค - ไใช่แต่ละคำ)

โค้ดต้นฉบับนับ character ทั่วทั้ง string ไม่ได้แยกตามคำ วิธีข้างต้นแยกคำก่อนแล้วนับในแต่ละคำ

Regex สำหรับ Word Boundary


// ใช้ Pattern หาคำ (Unicode aware)
Pattern wordPattern = Pattern.compile("\\p{L}+"); // ตัวอักษร Unicode 1+
Matcher m = wordPattern.matcher(sentence);
while (m.find()) {
    String word = m.group();
    // process word
}

ข้อควรระวัง

  • Punctuation: ควร strip ออกก่อนนับ (replaceAll("\\p{Punct}", ""))
  • Hyphenated words: "well-known" → 1 คำ หรือ 2 คำ? ขึ้นตาม spec
  • Contractions: "don't" → apostrophe
  • Unicode: ใช้ \\p{L} แทน [a-zA-Z]