在.net字符串比较:" + QUOT; VS" - "字符串、net、VS、QUOT

2023-09-03 15:45:05 作者:星星坠眼中

我一直认为的.Net比较字符串字典序,根据当前文化。但有一点很奇怪,当其中一个字符串结束对' - ':

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.

从 MSDN文档:

例如,培养可以指定字符的某些组合   被视为单个字符,或大写和小写字符   以特定方式进行比较,或一个字符的排列顺序   依赖于precede或按照它的字符。

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.

,以确保一致的字符逐个字符排序的唯一方法是使用序号比较,这表现在Anton's回答。

The only way to ensure consistent character-by-character ordering is by using an ordinal comparison, as demonstrated in Anton's answer.