精通 Java String compareTo():语法、用例与实战示例
Java 中 compareTo() 是什么?
compareTo() 按字典序比较两字符串。每字符转为 Unicode 值比较,返回 int 表示相对顺序。相同返回 0;调用字符串在前返回负值,在后返回正值。
该方法定义在 java.lang.Comparable 接口中。
语法
public int compareTo(String str)
参数:str —— 与调用字符串比较的字符串。
返回值:根据字典序返回负、零、正 int 值。
< 0—— 调用字符串字典序在前。== 0—— 两字符串相等。> 0—— 参数字符串字典序在前。
示例 1:基本用法
public class SampleString { public static void main(String[] args) { String str = "a"; System.out.println("Compare \"a\" to \"b\": " + str.compareTo("b")); str = "b"; System.out.println("Compare \"b\" to \"a\": " + str.compareTo("a")); str = "b"; System.out.println("Compare \"b\" to \"b\": " + str.compareTo("b")); } }
输出
- Compare "a" to "b": -1
- Compare "b" to "a": 1
- Compare "b" to "b": 0
解释:
- “a” 字母顺序在 “b” 前,结果为负。
- “b” 在 “a” 后,结果为正。
- 相同字符串得 0。
示例 2:大小写敏感 vs 不敏感
public class SampleString { public static void main(String[] args) { String str = "RockStar"; System.out.println("Case‑sensitive compare to \"rockstar\": " + str.compareTo("rockstar")); System.out.println("Case‑insensitive compare to \"ROCKSTAR\": " + str.compareToIgnoreCase("ROCKSTAR")); } }
输出
- Case‑sensitive compare to "rockstar": -32
- Case‑insensitive compare to "ROCKSTAR": 0
何时使用 compareTo()
需字符串自然(字典)排序时使用,如姓名列表排序、字典查找。遵循与 compareToIgnoreCase() 相同规则但区分大小写。
典型场景:
- 用
Collections.sort()排序String集合。 - 实现
Comparable的自定义类需字符串比较。 - 在已排序字符串数组上二分查找。
示例 3:实战比较
public class CompareDemo { public static void main(String[] args) { String s1 = "Guru1"; String s2 = "Guru2"; System.out.println("String 1: " + s1); System.out.println("String 2: " + s2); int result = s1.compareTo(s2); if (result < 0) { System.out.println("\"" + s1 + "\" is lexicographically higher than \"" + s2 + "\""); } else if (result == 0) { System.out.println("\"" + s1 + "\" is lexicographically equal to \"" + s2 + "\""); } else { System.out.println("\"" + s1 + "\" is lexicographically less than \"" + s2 + "\""); } } }
输出
- String 1: Guru1
- String 2: Guru2
- "Guru1" is lexicographically higher than "Guru2"
java
- Python print() 函数完全指南:基础用法、空行打印与自定义结束符
- Python str.count() 完全指南:统计字符与子串出现次数实战
- Python format() 字符串格式化完全指南:占位符、格式化规范、类与字典应用
- Java String length() 方法:获取字符串长度(示例)
- 精通 Java String.indexOf():定位子字符串与实战示例
- Java String.charAt() 详解:语法、返回类型、异常与实战示例
- Java String.contains() 方法:检查子字符串是否存在(实战示例)
- 精通 Java String.endsWith():检查字符串后缀(示例)
- Java 字符串替换大全:replace()、replaceAll() 与 replaceFirst() 详解
- Java BufferedReader 读取文件:实战指南与示例
- Java 中 char 与 String 相互转换:实用示例与最佳实践
- Java 递归反转字符串:原理、代码实现与性能分析