I always assumed that .Net compares strings lexicographically, according to the current culture. But there is something strange when one of the strings ends on '-':
"+".CompareTo("-")
Returns: 1
"+1".CompareTo("-1")
Returns: -1
I get it an all cultures I tried, including the invariant one. Can anyone explain what is going on, and how can I get the consistent character-by-character ordering for the current locale?
There isn't necessarily a consistent character-by-character ordering for any particular locale.
From the MSDN documentation:
For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.
The only way to ensure consistent character-by-character ordering is by using an ordinal comparison, as demonstrated in Anton's answer.
Try changing this to
string.Compare("+", "-", StringComparison.Ordinal); // == -2
string.Compare("+1", "-1", StringComparison.Ordinal); // == -2
string.Compare("+", "-"); string.Compare("+", "-", StringComparison.CurrentCulture); string.Compare("+", "-", StringComparison.InvariantCulture); string.Compare("+", "-", StringComparison.InvariantCultureIgnoreCase); // All Pass
the two value are equal because, inguisitic casing is being taken into consideration
FIX:
replace the invariant comparison with an ordinal comparison.This means the decisions are based on simple byte comparisons and ignore casing or equivalence tables that are parameterized by culture.
reference : Use ordinal StringComparison
string.Compare("+", "-", StringComparison.Ordinal); // fail
You'll probably want to use the true minus sign, Unicode codepoint \u2212. The minus sign you use in programming (\u002d) is a "hyphen-minus", its collation order is context sensitive because it is also frequently used as a hyphen. There's more than you'll want to know about the many different kind of dashes in this article.
use CompareOrdinal. e.g
String.CompareOrdinal("+1","-1");
-2
String.CompareOrdinal("+","-");
-2
来源:https://stackoverflow.com/questions/2244480/string-comparison-in-net-vs