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

一笑奈何 提交于 2019-11-28 11:58:53
LukeH

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!