我的基本理解是,Java compareTo方法lexicographically compares有两个字符串。我在这里读过一些基本知识,String Comparison in Java
我有以下例子:
public class CompareTo {
public static void main(String args[]) {
String str1 = "String";
String str2 = "compareTo";
String str3 = "String";
int var1 = str1.compareTo( str2 );
System.out.println("str1 & str2 comparison: "+var1);
int var2 = str1.compareTo( str3 );
System.out.println("str1 & str3 comparison: "+var2);
}
}我得到了var1 = -16和var2 = 0。
如果有人一步一步地向我解释这个Lexicographic comparison,那会有很大的帮助。
谢谢。
发布于 2017-03-23 06:54:41
好吧,如果你打印:
System.out.println ('S'-'c');你得到了-16
String的compareTo一次比较两个String的一个字符。第一对不相等的字符(在您的例子中是“字符串”的“S”和“compareTo”的“c”)决定结果。由于按字母顺序“S”位于'c‘之前,这个比较返回一个负值,这意味着"String“应该在"compareTo”之前。
在第二个比较中,所有对字符都是相等的,因此compareTo返回0。
发布于 2017-03-23 07:02:16
来自Java DOC
public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()在ASCII表c= 99 (小数)和S= 83 (小数)中
对此:S= -16
https://stackoverflow.com/questions/42969114
复制相似问题