The CompareTo in string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.