Sample code to illustrate:
int res1 = "a".CompareTo("A"); // res1 = -1
int res2 = "ab".CompareTo("A"); // res2 = 1
I'm seeing res1 = -1
, and res2 = 1
at the end, which was a bit unexpected.
I thought res1
would return 1, since on an ASCII chart "A" (0x41) comes before "a" (0x61).
Also, it seems strange that for res2
, the length of the string seems to make a difference. i.e. if "a" comes before "A" (as res1 = -1
indicates), then I would have thought that "a"withAnythingAfterIt would also come before "A"withAnythingAfterIt.
Can someone shed some light? Thanks.
The String. CompareTo instance methods always perform an ordinal case-sensitive comparison. They are primarily suited for ordering strings alphabetically.
The compareToIgnoreCase() method compares two strings lexicographically, ignoring lower case and upper case differences. The comparison is based on the Unicode value of each character in the string converted to lower case. The method returns 0 if the string is equal to the other string, ignoring case differences.
The Java String compareTo() method compares two strings lexicographically (in the dictionary order), ignoring case differences.
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
This is the expected behavior. String.CompareTo(string)
does a culture sensitive comparison, using its sort order. In fact it calls CultureInfo
to do the job as we can see in the source code:
public int CompareTo(String strB) {
if (strB==null) {
return 1;
}
return CultureInfo.CurrentCulture.CompareInfo.Compare(this, strB, 0);
}
Your current culture puts 'A' after 'a' in the sort order, since it would be a tie, but not after 'ab' since clearly 'ab' comes after either 'a' or 'A' in most sort orders I know. It's just the tie breaking mechanism doing its work: when the sort order would be the same, use the ordinal value!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With