.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“-"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)