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

So sánh hai chuỗi String trong Java

So sánh hai chuỗi dùng phương thức compareTo() trong Java. Cú pháp:

int compareTo(Object o)

Ở đây, o là đối tượng cần so sánh.

Giá trị trả về: 0 nếu argument bằng chuỗi này theo thứ tự từ điển; nhỏ hơn 0 nếu argument lớn hơn chuỗi này theo thứ tự từ điển; lớn hơn 0 nếu argument nhỏ hơn chuỗi này theo thứ tự từ điển.

Ví dụ 1: compareTo()

public class Demo {
    public static void main(String args[]) {
        String str1 = "Strings are immutable";
        String str2 = new String("Strings are immutable");
        String str3 = new String("Integers are not immutable");
        
        int result = str1.compareTo(str2);
        System.out.println(result); // 0
        
        result = str2.compareTo(str3);
        System.out.println(result); // 10
    }
}

Kết quả

0
10

Ví dụ 2: compareToIgnoreCase() - Bỏ qua chữ hoa/thường

Phương thức này trả về số âm, 0, hoặc số dương tùy chuỗi chỉ định lớn hơn, bằng, hoặc nhỏ hơn chuỗi này, bỏ qua chữ hoa/thường.

int compareToIgnoreCase(String str)

Ví dụ

public class Demo {
    public static void main(String args[]) {
        String str1 = "Strings are immutable";
        String str2 = "Strings are immutable";
        String str3 = "Integers are not immutable";
        
        int result = str1.compareToIgnoreCase(str2);
        System.out.println(result); // 0
        
        result = str2.compareToIgnoreCase(str3);
        System.out.println(result); // 10
        
        result = str3.compareToIgnoreCase(str1);
        System.out.println(result); // -10
    }
}

Kết quả

0
10
-10

Lưu ý quan trọng: == so sánh tham chiếu (reference), equals() so sánh nội dung, compareTo() so sánh thứ tự từ điển (lexicographical). Dùng equals() khi chỉ cần kiểm tra bằng nhau.