.Net 中的字符串比较:“+"vs“-"

String comparison in .Net: quot;+quot; vs quot;-quot;(.Net 中的字符串比较:“+vs“-)

本文介绍了.Net 中的字符串比较:“+"vs“-"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为 .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 文档:

例如,一种文化可以指定某些字符组合被视为单个字符,或大写和小写字符以特定的方式进行比较,或者说一个字符的排序顺序取决于它前面或后面的字符.

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.

这篇关于.Net 中的字符串比较:“+"vs“-"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:.Net 中的字符串比较:“+"vs“-"

基础教程推荐