Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Trích xuất từ bắt đầu bằng nguyên âm và độ dài n trong Java

Tách chuỗi thành từ, lọc từ bắt đầu bằng nguyên âm (a,e,i,o,u,A,E,I,O,U) và có độ dài bằng n.

Ví dụ hoàn chỉnh


import java.io.*;
import java.util.*;

public class VowelWordsLengthN {
    public static void main(String[] args) throws IOException {
        // Đọc file
        String content = Files.readString(Paths.get("D:/sample.txt"));
        
        int n = 5; // độ dài mong muốn
        
        // Tách từ (regex: 1 hoặc nhiều whitespace)
        String[] words = content.split("\\s+");
        
        System.out.println("Từ bắt đầu bằng nguyên âm, độ dài " + n + ":");
        for (String word : words) {
            if (word.length() == n && startsWithVowel(word)) {
                System.out.println(word);
            }
        }
    }
    
    static boolean startsWithVowel(String word) {
        if (word.isEmpty()) return false;
        char first = Character.toLowerCase(word.charAt(0));
        return first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u';
    }
}

Kết quả mẫu (với n=5)


Từ bắt đầu bằng nguyên âm, độ dài 5:
origin
ideal
exist
about
other

Cải tiến: Xử lý dấu câu

Từ có thể kèm dấu câu: "originated," → cần strip punctuation.


String clean = word.replaceAll("\\p{Punct}", ""); // xóa dấu câu
if (clean.length() == n && startsWithVowel(clean)) { ... }

Java 8+ Stream (ngắn gọn)


Arrays.stream(content.split("\\s+"))
      .map(w -> w.replaceAll("\\p{Punct}", ""))
      .filter(w -> w.length() == n && startsWithVowel(w))
      .distinct()
      .sorted()
      .forEach(System.out::println);

Mở rộng: Tìm từ bắt đầu bằng bất kỳ ký tự nào


public static List findWords(String text, Set startChars, int length) {
    return Arrays.stream(text.split("\\s+"))
        .map(w -> w.replaceAll("\\p{Punct}", ""))
        .filter(w -> w.length() == length)
        .filter(w -> startChars.contains(Character.toLowerCase(w.charAt(0))))
        .collect(Collectors.toList());
}