Home  >  Article  >  Java  >  How to compare string sizes in java

How to compare string sizes in java

王林
王林Original
2020-05-14 13:46:194283browse

How to compare string sizes in java

You can use the String.compareTo method for comparison.

The return value of the compareTo() method is int, which compares the size of the corresponding characters according to the ASCII code table.

1. If the strings are equal, the return value is 0;

2. If the first character is not equal to the first character of the parameter, end the comparison and return the difference between them ( ascii code value) (the value of the string before the negative value is smaller than the string after it, and the string before the positive value is greater than the string after it);

3. If the first character is equal to the first character of the parameter, Then compare the second character with the second character of the parameter, and so on, until either the character being compared or the character being compared is completely compared, then the length of the characters is compared.

(Video tutorial recommendation: java video)

Specific example:

String s1 = "abc"; 
String s2 = "abcd"; 
String s3 = "abcdfg"; 
String s4 = "1bcdfg"; 
String s5 = "cdfg"; 
System.out.println( s1.compareTo(s2) ); // -1 (前面相等,s1长度小1) 
System.out.println( s1.compareTo(s3) ); // -3 (前面相等,s1长度小3) 
System.out.println( s1.compareTo(s4) ); // 48 ("a"的ASCII码是97,"1"的的ASCII码是49,所以返回48) 
System.out.println( s1.compareTo(s5) ); // -2 ("a"的ASCII码是97,"c"的ASCII码是99,所以返回-2)

Related tutorial recommendation: java entry program

The above is the detailed content of How to compare string sizes in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn