Return Value of compareTo () method of String

Source: Internet
Author: User

In the past, compareTo () was used to compare the total size of ASCII codes. CompareTo (), which is used to compare the size of the corresponding characters (ASCII order) first. If the first character is different from the first character of the parameter, end the comparison and return the difference between them, if the first character is the same as the first character of the parameter, compare the second character with the second character of the parameter, and so on, the length of the character to be compared is compared until all the characters to be compared or compared are compared. example: www.2cto. comString s1 = "abc"; String s2 = "abcd"; String s3 = "abcdfg"; String s4 = "1 bcdfg"; String s5 = "cdfg"; System. out. println (s1.compareTo (s2); //-1 (equal front, 1 smaller s1 length) System. out. println (s1.compareTo (s3); //-3 (equal front, small s1 length 3) System. out. println (s1.compareTo (s4); // 48 (the ASCII code of "a" is 97, and the ASCII code of "1" is 49, so 48 is returned) System. out. println (s1.compareTo (s5); //-2 (the ASCII code of "a" is 97, and the ASCII code of "c" is 99, So-2 is returned)

Related Article

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.