string.compareTo(anOtherString);
I want to compare two strings with the method string.compareTo(anOtherString); and it delivers me a strange value... (i need an integer value between 0 and 57 for every string) In the following example the first line delivers 2 and the second 1.
System.out.println("And".compareTo("A"));
System.out.println("Bus".compareTo("A"));
I expected that the first line is 1 and the second 2... Can someone explain that to me? 开发者_运维知识库
Is there a better possibility to do that?
Thanks.
Read the documentation for String.compareTo():
If they have different characters at one or more index positions ... compareTo returns the difference of the two character values at position k in the two string. If there is no index position at which they differ ... compareTo returns the difference of the lengths of the strings.
If the result is > 0, then the first string is greater, lexicographically by UTF-16 code unit. If the result is < 0, then the first string is lesser, lexicographically.
You shouldn't rely on the actual value besides the sign and whether or not it is zero.
From http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#compareTo(java.lang.String)
Returns: the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
Btw, if you want locale-sensitive comparison, e.g. if you're comparing human readable text, use java.text.Collator.compare instead.
精彩评论