c# - 为什么 string.Compare 似乎不一致地处理重音字符?

标签 c# sorting diacritics string-comparison

如果我执行下面的语句:

string.Compare("mun", "mün", true, CultureInfo.InvariantCulture)

结果为'-1',表示'mun'的数值小于'mün'。

但是,如果我执行这条语句:

string.Compare("Muntelier, Schweiz", "München, Deutschland", true, CultureInfo.InvariantCulture)

我得到“1”,表示“Muntelier, Schewiz”应该排在最后。

这是比较中的错误吗?或者,更有可能的是,在对包含重音符号的字符串进行排序时,是否应该考虑一条规则


这是一个问题的原因是,我正在对列表进行排序,然后执行手动二进制过滤器,这意味着获取以“xxx”开头的每个字符串。

以前我使用的是Linq 'Where' 方法,但现在我必须使用这个由另一个人编写的自定义函数,因为他说它性能更好。

但是自定义函数似乎没有考虑 .NET 具有的任何“unicode”规则。因此,如果我告诉它按“mün”过滤,它不会找到任何项目,即使列表中有以“mun”开头的项目。

这似乎是因为重音字符的顺序不一致,这取决于重音字符后面的字符。


好的,我想我已经解决了这个问题。

在过滤器之前,我根据每个字符串的前 n 个字母进行排序,其中 n 是搜索字符串的长度。

最佳答案

有一个打破平局的算法在起作用,参见http://unicode.org/reports/tr10/

To address the complexities of language-sensitive sorting, a multilevel comparison algorithm is employed. In comparing two words, for example, the most important feature is the base character: such as the difference between an A and a B. Accent differences are typically ignored, if there are any differences in the base letters. Case differences (uppercase versus lowercase), are typically ignored, if there are any differences in the base or accents. Punctuation is variable. In some situations a punctuation character is treated like a base character. In other situations, it should be ignored if there are any base, accent, or case differences. There may also be a final, tie-breaking level, whereby if there are no other differences at all in the string, the (normalized) code point order is used.

因此,“Munt...”和“Münc...”在字母顺序上是不同的,并根据“t”和“c”排序。

然而,“mun”和“mün”在字母顺序上是相同的(“u”等同于失落语言中的“ü”)所以比较字符代码

关于c# - 为什么 string.Compare 似乎不一致地处理重音字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1371813/

相关文章:

javascript - 减少对象数组: limit similar fields based on value from another field

php - 进行变音符号敏感搜索

python - 阅读带重音的文本 - Python

c# - FileHelpers -- 只读取第 N 列

c# - 如果它有多个值,如何返回查询字符串的第一个值?

excel - 按值对 Excel 列进行排序

c# - 我怎样才能 "decode"C# 中的 `ç` 值

c# - 构建代码以允许多个开发人员更新构造函数的最佳方法是什么

c# - 如何从排除的更改中删除项目

linux - Bash - 对文件中的行进行排序