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

Kiểm tra chuỗi chứa chuỗi con bỏ qua hoa/thường với Apache Commons Lang

Thư viện Apache Commons Lang cung cấp tiện ích StringUtils.containsIgnoreCase() để kiểm tra chuỗi con không phân biệt chữ hoa/thường – cách ngắn gọn và an toàn hơn so với việc tự chuyển toLowerCase().

Thiết lập Maven


<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version> <!-- phiên bản mới -->
</dependency>

Cú pháp


public static boolean containsIgnoreCase(CharSequence str, CharSequence searchStr)
  • Trả về true nếu str chứa searchStr (bỏ qua hoa/thường)
  • An toàn với null: trả về false nếu bất kỳ tham số nào là null

Ví dụ: Tìm kiếm trong file văn bản


import java.io.File;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;

public class ContainsIgnoreCaseDemo {
    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 tìm kiếm: ");
        String keyword = sc.nextLine();
        
        String content = readFile("D:/sample.txt");
        boolean found = StringUtils.containsIgnoreCase(content, keyword);
        
        System.out.println(found ? "File chứa từ khóa!" : "File KHÔNG chứa từ khóa.");
    }
}

Kết quả mẫu


Nhập từ khóa tìm kiếm: comforts of their drawing rooms
File chứa từ khóa!

Tại sao dùng StringUtils? Xử lý null an toàn, hiệu năng tốt, code dễ đọc hơn so với str.toLowerCase().contains(sub.toLowerCase()).