The compareTo() method of the String class in Java compares strings in detail

Center: String is a string, and its comparison uses the compareTo method. It starts from the first place and compares it. If it encounters different characters, it immediately returns the difference between the ascii values ​​of the two characters. The return value is int type

1. When the two compared strings are in English and have different lengths,

1) The short-length is the same as the long-length character, and the returned result is a value of two subtracted lengths

a="hello";
b="hell";
num=1;
or
a="h";
b=" hello";
num=4;

2) The length is not the same and the first few characters are not the same, starting from the first digit, when a different character is found, the returned value is the comparison value of the two characters

a= "assdf";
b="bdd";

num=-1;

2. When the two compared strings are in English and have the same length,

1) a character

a="a"; //97
b="b"; //98

num = -1;

2) For multiple characters, if the first character is different, compare the first character directly
a="ah"; //a=97
b="eg"; //e=101

num = -4


3) For multiple characters, if the first character is the same, the second character is directly compared, and so on

a="ae";   //e=101
b="aa";   //a=97
num=4;

Reprinted source: https://blog.csdn.net/qq_34115598/article/details/79892478

Center: String is a string, and its comparison uses the compareTo method. It starts from the first place and compares it. If it encounters different characters, it immediately returns the difference between the ascii values ​​of the two characters. The return value is int type

1. When the two compared strings are in English and have different lengths,

1) The short-length is the same as the long-length character, and the returned result is a value of two subtracted lengths

a="hello";
b="hell";
num=1;
or
a="h";
b=" hello";
num=4;

2) The length is not the same and the first few characters are not the same, starting from the first digit, when a different character is found, the returned value is the comparison value of the two characters

a= "assdf";
b="bdd";

num=-1;

2. When the two compared strings are in English and have the same length,

1) a character

a="a"; //97
b="b"; //98

num = -1;

2) For multiple characters, if the first character is different, compare the first character directly
a="ah"; //a=97
b="eg"; //e=101

num = -4


3) For multiple characters, if the first character is the same, the second character is directly compared, and so on

a="ae";   //e=101
b="aa";   //a=97
num=4;

Guess you like

Origin blog.csdn.net/publicstaticfinal/article/details/90549462