Java String compareTo(String anotherString)
方法按字典顺序比较两个字符串。
语法
以下是此方法的语法 -
int compareTo(String anotherString)
参数
anotherString
- 要比较的String
对象值。
返回值
如果参数是一个按字典顺序排列等于该字符串的字符串,则返回值为0
; 如果参数是按字典顺序大于此字符串的字符串,则返回值小于0
; 如果参数是按字典顺序小于此字符串的字符串,则返回值大于0
。
示例
public class Test {
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.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
result = str3.compareTo( str1 );
System.out.println(result);
}
}
执行上面示例代码,得到以下结果:
0
10
-10
上一篇:
java中方法重载和方法重写的区别
下一篇:无