什么是 java String compareTo 方法和什么是字典顺序的 Java
What is java String compareTo method and What is Java lexicographically
不知道输出是什么意思?有人会帮我吗?请解释一下它是如何工作的。
public class LastIndexOfExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
}
}
那么输出是:
0
-5
-1
来自 compareTo
javadoc:
If there is an index at which the two strings differ, the result is
the difference between the two char's at the lowest such index
完整的 Javadoc:
/**
* Compares this string to the given string.
*
* <p>The strings are compared one {@code char} at a time.
* In the discussion of the return value below, note that {@code char} does not
* mean code point, though this should only be visible for surrogate pairs.
*
* <p>If there is an index at which the two strings differ, the result is
* the difference between the two {@code char}s at the lowest such index.
* If not, but the lengths of the strings differ, the result is the difference
* between the two strings' lengths.
* If the strings are the same length and every {@code char} is the same, the result is 0.
*
* @throws NullPointerException
* if {@code string} is {@code null}.
*/
public native int compareTo(String string);
并来自联机文档(link 以上):
The result is a negative integer if this String object
lexicographically precedes the argument string
不知道输出是什么意思?有人会帮我吗?请解释一下它是如何工作的。
public class LastIndexOfExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
}
}
那么输出是: 0 -5 -1
来自 compareTo
javadoc:
If there is an index at which the two strings differ, the result is the difference between the two char's at the lowest such index
完整的 Javadoc:
/**
* Compares this string to the given string.
*
* <p>The strings are compared one {@code char} at a time.
* In the discussion of the return value below, note that {@code char} does not
* mean code point, though this should only be visible for surrogate pairs.
*
* <p>If there is an index at which the two strings differ, the result is
* the difference between the two {@code char}s at the lowest such index.
* If not, but the lengths of the strings differ, the result is the difference
* between the two strings' lengths.
* If the strings are the same length and every {@code char} is the same, the result is 0.
*
* @throws NullPointerException
* if {@code string} is {@code null}.
*/
public native int compareTo(String string);
并来自联机文档(link 以上):
The result is a negative integer if this String object lexicographically precedes the argument string