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

Kiểm tra chuỗi chứa chuỗi con không phân biệt hoa/thường (cách thủ công)

Ngoài StringUtils.containsIgnoreCase() (Apache Commons), ta có thể tự triển khai bằng cách chuyển cả hai chuỗi về cùng chữ thường/hoa rồi dùng contains().

Thuật toán

  1. Lấy chuỗi gốc và chuỗi cần tìm
  2. Chuyển cả hai về toLowerCase() (hoặc toUpperCase())
  3. Dùng contains() trên chuỗi đã chuyển đổi

Ví dụ: Tìm kiếm trong file


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

public class SubstringIgnoreCaseManual {
    public static String readFile(String path) throws Exception {
        StringBuilder sb = new StringBuilder();
        try (Scanner sc = new Scanner(new File(path))) {
            while (sc.hasNextLine()) {
                sb.append(sc.nextLine()).append("\n");
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.print("Nhập từ khóa: ");
        String keyword = sc.nextLine();
        
        String content = readFile("D:/sample.txt");
        
        // Chuyển về lower case để so sánh
        String lowerContent = content.toLowerCase();
        String lowerKeyword = keyword.toLowerCase();
        
        boolean found = lowerContent.contains(lowerKeyword);
        System.out.println(found ? "Tìm thấy!" : "Không tìm thấy.");
    }
}

Kết quả


Nhập từ khóa: comforts of their drawing rooms
Tìm thấy!

⚠️ Lưu ý hiệu năng & Unicode

  • Tạo 2 chuỗi mới → tốn bộ nhớ nếu chuỗi lớn
  • toLowerCase() dùng locale mặc định, có thể sai với một số ngôn ngữ (Turkish 'i' vs 'İ')
  • Khuyến nghị: Dùng StringUtils.containsIgnoreCase() hoặc Pattern.compile(regex, Pattern.CASE_INSENSITIVE) cho production

Cách dùng Pattern (chuẩn Unicode)


import java.util.regex.*;

boolean found = Pattern.compile(Pattern.quote(keyword), Pattern.CASE_INSENSITIVE)
                       .matcher(content)
                       .find();