Java String compareTo()
compareTo() 方法用來比較兩個字串的字典順序(lexicographical order)。
語法
string.compareTo(String anotherString)
string.compareToIgnoreCase(String str)
回傳值
- 負數:呼叫的字串小於參數字串
- 0:兩字串相等
- 正數:呼叫的字串大於參數字串
範例
String s1 = "apple";
String s2 = "banana";
String s3 = "apple";
System.out.println(s1.compareTo(s2)); // -1(a < b)
System.out.println(s2.compareTo(s1)); // 1(b > a)
System.out.println(s1.compareTo(s3)); // 0(相等)
比較規則
逐字元比較 Unicode 值:
// 比較首字元
System.out.println("a".compareTo("b")); // -1(97 - 98)
System.out.println("b".compareTo("a")); // 1(98 - 97)
// 首字元相同,比較下一個
System.out.println("ab".compareTo("ac")); // -1
System.out.println("abc".compareTo("abd")); // -1
// 長度不同
System.out.println("abc".compareTo("ab")); // 1(多一個字元)
System.out.println("ab".compareTo("abc")); // -1(少一個字元)
大小寫
大寫字母的 Unicode 值小於小寫字母:
System.out.println("A".compareTo("a")); // -32(65 - 97)
System.out.println("a".compareTo("A")); // 32(97 - 65)
System.out.println("Apple".compareTo("apple")); // -32
System.out.println("apple".compareTo("Apple")); // 32
compareToIgnoreCase()
忽略大小寫比較:
System.out.println("Apple".compareToIgnoreCase("apple")); // 0
System.out.println("HELLO".compareToIgnoreCase("hello")); // 0
System.out.println("abc".compareToIgnoreCase("ABD")); // -1
實際應用
排序字串
String[] fruits = {"Banana", "apple", "Cherry"};
// 區分大小寫排序(大寫會排在前面)
Arrays.sort(fruits);
System.out.println(Arrays.toString(fruits));
// [Banana, Cherry, apple]
// 忽略大小寫排序
Arrays.sort(fruits, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(fruits));
// [apple, Banana, Cherry]
自訂排序
List<String> names = Arrays.asList("Alice", "bob", "Charlie");
// 使用 compareTo
Collections.sort(names, (a, b) -> a.compareTo(b));
// 使用 compareToIgnoreCase
Collections.sort(names, (a, b) -> a.compareToIgnoreCase(b));
範圍檢查
String input = "dog";
// 檢查是否在 "cat" 和 "fish" 之間
if (input.compareTo("cat") > 0 && input.compareTo("fish") < 0) {
System.out.println(input + " 在範圍內");
}
找出最大/最小字串
String[] words = {"banana", "apple", "cherry", "date"};
String min = words[0];
String max = words[0];
for (String word : words) {
if (word.compareTo(min) < 0) min = word;
if (word.compareTo(max) > 0) max = word;
}
System.out.println("最小:" + min); // apple
System.out.println("最大:" + max); // date
compareTo vs equals
| 方法 | 用途 | 回傳值 |
|---|---|---|
equals() | 檢查是否相等 | boolean |
compareTo() | 比較大小順序 | int |
String s1 = "apple";
String s2 = "apple";
// 只需要檢查相等,使用 equals()
if (s1.equals(s2)) {
System.out.println("相等");
}
// 需要知道大小關係,使用 compareTo()
if (s1.compareTo(s2) == 0) {
System.out.println("相等");
}