简体   繁体   中英

String comparison in .Net: “+” vs “-”

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?

Try changing this to

string.Compare("+", "-", StringComparison.Ordinal); // == -2
string.Compare("+1", "-1", StringComparison.Ordinal); // == -2

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 .

  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 \−. The minus sign you use in programming (\-) 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 . eg

String.CompareOrdinal("+1","-1");
-2
String.CompareOrdinal("+","-");
-2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM