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“-"
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01