使用Java中的compareTo()方法比较两个字符串。语法如下-int compareTo(Object o)

在这里,o是要比较的对象。

如果参数在字典上等于该字符串,则返回值为0;否则,返回值为0。如果参数在字典上大于此字符串,则该值小于0;如果参数在字典上小于此字符串,则该值大于0。

示例

现在让我们看一个例子-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);
result = str2.compareTo( str3 );
System.out.println(result);
}
}

输出结果0

10

让我们看另一个示例,其中我们按照字典顺序比较两个字符串,而忽略使用compareToIgnoreCase()的大小写差异。当指定的String大于,等于或小于此String时,此方法将返回负整数,零或正整数,而忽略大小写考虑。

语法如下-int compareToIgnoreCase(String str)

在这里,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);
result = str2.compareToIgnoreCase( str3 );
System.out.println(result);
result = str3.compareToIgnoreCase( str1 );
System.out.println(result);
}
}

输出结果0

10

-10