String comparison in .Net: quot;+quot; vs quot;-quot;(.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“-"


- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01