If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case,compareToreturns the difference of the lengths of the strings -- that is, the value: this.length()-anotherString.length() 1.当字符串s1和s都表示数字时,有三...
ExampleGet your own Java Server Compare two strings: StringmyStr1="Hello";StringmyStr2="Hello";System.out.println(myStr1.compareTo(myStr2));// Returns 0 because they are equal Try it Yourself » Definition and Usage ThecompareTo()method compares two strings lexicographically. ...
Java 8引入了lambda表达式,可以更加简洁地实现排序逻辑。 importjava.util.Arrays;publicclassStringSort{publicstaticvoidmain(String[]args){String[]strings={"apple","banana","grape"};Arrays.sort(strings,(str1,str2)->str1.length()-str2.length());for(Stringstr:strings){System.out.println(str);}}...
int java.lang.String.compareTo(String anotherString)Compares two stringslexicographically(字典序; 按字典顺序;). The comparison is based on theUnicodevalue of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence re...
Example 2: Check if Two Strings are Equal classMain{publicstaticvoidmain(String[] args){ String str1 ="Learn Python"; String str2 ="Learn Java";// if str1 and str2 are equal, the result is 0 if(str1.compareTo(str2) ==0) { ...
不是要用return a.compareTo(b);进行比较的吗?compareTo()方法是在String类下面的 Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to ...
publicclassTest{publicstaticvoidmain(Stringargs[]){Stringstr1="Strings";Stringstr2="Strings";Stringstr3="Strings123";intresult=str1.compareTo(str2);System.out.println(result);result=str2.compareTo(str3);System.out.println(result);result=str3.compareTo(str1);System.out.println(result);}} ...
在Java中,可以使用compareTo方法来比较字符串。 public class CompareStrings { public static void main(String[] args) { String str1 = "Hello"; String str2 = "World"; int result = str1.compareTo(str2); if(result < 0) { System.out.println("str1 is less than str2"); } else if(...
publicclassTest{publicstaticvoidmain(Stringargs[]){Stringstr1="Strings";Stringstr2="Strings";Stringstr3="Strings123";intresult=str1.compareTo(str2);System.out.println(result);result=str2.compareTo(str3);System.out.println(result);result=str3.compareTo(str1);System.out.println(result);}} ...
Java String.compareTo() 方法是以区分大小写的方式按字典顺序比较两个字符串。对于不区分大小写的比较,请使用compareToIgnoreCase()方法。 字符串的字典顺序 如果一个字符串 ‘string1’ 在字典中出现在另一个字符串 ‘string2′ 之前,那么可以说在字符串比较中,’string2’ 大于 ‘string1’。