compareTo的用法

这是自然比较方法,比较字典顺序的规则,如果两个字符串的第一个字符不相等,则都按第一个字符的ASCII码比较,并返回一个整形
示例:
| 12
 3
 4
 5
 6
 7
 
 | public class test{public static void main(Stirng[] args){
 String str1 = "abc";
 String str2 = "IloveU";
 System.out.println(st1.compareTo(str2));
 }
 }
 
 | 
运行结果为24(a为97,I为73,相减24)
如果第一个字符都相等,那么就以两个字符串的第二个字符串开始比较,以此类推
| 12
 3
 4
 5
 6
 7
 
 | public class test{public static void main(Stirng[] args){
 String str1 = "aIloveU520";
 String str2 = "abc";
 System.out.println(st1.compareTo(str2));
 }
 }
 
 | 
运行结果为-25
如果两个字符串的前几位字符都相同,但字符串2比字符串1多几位字符,那么就以字符串的长度进行比较
| 12
 3
 4
 5
 6
 7
 
 | public class test{public static void main(Stirng[] args){
 String str1 = "mjh";
 String str2 = "mjhdsb";
 System.out.println(st1.compareTo(str2));
 }
 }
 
 | 
运行结果为-7