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

วิธีดึงคำที่ขึ้นต้นด้วยสระและมีความยาวเท่ากับ n ใน Java

โจทย์: จากข้อความ ให้ดึงคำที่ ขึ้นต้นด้วยสระ (a, e, i, o, u) และมี ความยาวเท่ากับ n

ตัวอย่างโค้ดพื้นฐาน (เฉพาะขึ้นต้นด้วยสระ)


import java.io.File;
import java.util.Scanner;

public class WordsStartWithVowel {
    public static String fileToString(String filePath) throws Exception {
        Scanner sc = new Scanner(new File(filePath));
        StringBuilder sb = new StringBuilder();
        while (sc.hasNextLine()) {
            sb.append(sc.nextLine()).append(" ");
        }
        return sb.toString();
    }
    
    public static void main(String[] args) throws Exception {
        String text = fileToString("D:\\sample.txt");
        String[] words = text.split("\\s+"); // split by whitespace
        
        for (String word : words) {
            if (word.isEmpty()) continue;
            char first = Character.toLowerCase(word.charAt(0));
            if (first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u') {
                System.out.println(word);
            }
        }
    }
}

ผลลัพธ์ (จากตัวอย่างข้อความ)


originated
idea
exists
a
of
on-line
and
at
own
of

เวอร์ชันครบถ้วน: กรองขึ้นต้นสระ + ความยาว = n


import java.util.*;
import java.util.regex.Pattern;

public class VowelWordsLengthN {
    private static final Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
    
    public static List findWords(String text, int length) {
        List result = new ArrayList<>();
        String[] words = text.split("\\s+");
        
        for (String word : words) {
            // ลบ punctuation รอบๆ คำ (optional)
            String cleanWord = word.replaceAll("^[^a-zA-Z]+|[^a-zA-Z]+$", "");
            
            if (cleanWord.length() == length && !cleanWord.isEmpty()) {
                char first = cleanWord.charAt(0);
                if (VOWELS.contains(first)) {
                    result.add(cleanWord);
                }
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        String text = "Apple orange banana elephant igloo umbrella cat dog ant";
        int n = 5;
        
        List words = findWords(text, n);
        System.out.println("Words starting with vowel, length " + n + ": " + words);
    }
}

ผลลัพธ์


Words starting with vowel, length 5: [Apple, elephant, igloo]

วิธีทางเลือก: ใช้ Regex เดียว


import java.util.regex.*;

public class VowelWordsRegex {
    public static void main(String[] args) {
        String text = "Apple orange banana elephant igloo umbrella cat dog ant";
        int n = 5;
        
        // \\b = word boundary, (?i) = case insensitive
        String regex = "(?i)\\b[aeiou]\\w{" + (n-1) + "}\\b";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

ผลลัพธ์


Apple
elephant
igloo

ข้อควรระวัง

  • split("\\s+") แยกคำด้วย whitespace หลายตัว (space, tab, newline)
  • คำที่มี punctuation (comma, period) ควร clean ก่อนเช็คความยาว
  • Unicode vowels (ภาษาอื่น) ต้องขยาย VOWELS set
  • Regex \\w รวม underscore และตัวเลข - อาจไม่ตรงกับ "คำ" อย่างเคร่งครัด

ขยาย: นับจำนวนคำแต่ละคำที่ขึ้นต้นสระ


Map counts = Arrays.stream(text.split("\\s+"))
    .filter(w -> !w.isEmpty())
    .map(w -> w.replaceAll("^[^a-zA-Z]+|[^a-zA-Z]+$", ""))
    .filter(w -> VOWELS.contains(w.charAt(0)))
    .collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));