In the API source code, the CompareTo of string is actually an ASCII code that compares two strings at a time. If the ASCII equality of two strings continues the subsequent comparison, otherwise the two ASCII difference is returned directly. Returns 0 if two strings are exactly the same. The following is the source code:
Public intcompareTo (String anotherstring) {intLen1 =count; intLen2 =Anotherstring.count; //gets the shorter length of the two strings intn =math.min (Len1, len2); CharV1[] =value; CharV2[] =Anotherstring.value; inti =offset; intj =Anotherstring.offset; if(i = =j) {intK =i; intLim = n +i; while(K <Lim) {CharC1 =V1[k]; CharC2 =V2[k]; //if the two-character ASC is not the same, return directlyif(C1! =C2) { returnC1-C2; } k++; } } Else { while(n--! = 0) { CharC1 = v1[i++]; CharC2 = v2[j++]; //if the two-character ASC is not the same, return directly if(C1! =C2) { returnC1-C2; } } } //if all are the same, return the length of the two string to check returnLEN1-Len2; }
By the above code, we can easily calculate the value of the CompareTo of two strings:
int i1 = "ABCD". CompareTo ("ADHF");
int i2 = "abc". COMPARETO ("abcdef");
int i3 = "ABCD". CompareTo ("abc");
System.out.println (i1);//-2
System.out.println (I2);-3
SYSTEM.OUT.PRINTLN (i3); 0
Example: Practical application of CompareTo? For simple string sorting. (for example, using CompareTo to sort names)
//use a simple looping order for(inti = 0; i < array.length-1; i++) { for(intj = i + 1; J < Array.Length; J + +) { if(Array[i].compareto (array[j]) > 0) {String temp=Array[i]; Array[i]=Array[j]; ARRAY[J]=temp; } } } for(inti = 0; I < 5; i++) {System.out.println (array[i]); } }
After sorting the string above, the contents of the strings will be:
James Libai Lilei Owen Wolf
The CompareTo in string