เปรียบเทียบ String สองตัวใน Java ด้วยเมธอด compareTo() Syntax:
int compareTo(Object o)
o คือ Object ที่ต้องการเปรียบเทียบ
ค่า Return:
0- Argument เป็น String เท่ากัน Lexicographically< 0- Argument มากกว่า Lexicographically> 0- Argument น้อยกว่า Lexicographically
ตัวอย่างที่ 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
}
}
ผลลัพธ์
0
10
ตัวอย่างที่ 2: compareToIgnoreCase() - เปรียบเทียบไม่สนใจ Case
Syntax: int compareToIgnoreCase(String str)
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
}
}
ผลลัพธ์
0
10
-10
สรุป: ใช้ compareTo() สำหรับ Case-sensitive, ใช้ compareToIgnoreCase() สำหรับ Case-insensitive คืนค่า Negative/Zero/Positive ตามลำดับ Lexicographical