问题描述
我想知道比较两个忽略大小写的字符的正确方法适用于所有文化.另外, Comparer
是在不忽略大小写的情况下测试两个字符的最佳方法吗?这适用于代理对吗?
I'm wondering what the correct way to compare two characters ignoring case that will work for all cultures. Also, is Comparer<char>.Default
the best way to test two characters without ignoring case? Does this work for surrogate-pairs?
编辑:添加示例 IComparer
实现
如果这对任何人有帮助,这就是我决定使用的方法
If this helps anyone this is what I've decided to use
public class CaseInsensitiveCharComparer : IComparer<char> {
private readonly System.Globalization.CultureInfo ci;
public CaseInsensitiveCharComparer(System.Globalization.CultureInfo ci) {
this.ci = ci;
}
public CaseInsensitiveCharComparer()
: this(System.Globalization.CultureInfo.CurrentCulture) { }
public int Compare(char x, char y) {
return Char.ToUpper(x, ci) - Char.ToUpper(y, ci);
}
}
// Prints 3
Console.WriteLine("This is a test".CountChars('t', new CaseInsensitiveCharComparer()));
推荐答案
这取决于您所说的为所有文化工作"是什么意思.即使在土耳其,您是否希望i"和I"相等?
It depends on what you mean by "work for all cultures". Would you want "i" and "I" to be equal even in Turkey?
你可以使用:
bool equal = char.ToUpperInvariant(x) == char.ToUpperInvariant(y);
...但是根据您对有效"的理解,我不确定根据所有文化是否有效".
... but I'm not sure whether that "works" according to all cultures by your understanding of "works".
当然,您可以将两个字符都转换为字符串,然后对字符串执行任何您想要的比较.效率稍低,但它确实为您提供了框架中可用的所有比较范围:
Of course you could convert both characters to strings and then perform whatever comparison you want on the strings. Somewhat less efficient, but it does give you all the range of comparisons available in the framework:
bool equal = x.ToString().Equals(y.ToString(),
StringComparison.InvariantCultureIgnoreCase);
对于代理对,Comparer
无论如何都不可行,因为您没有单个 char
.你可以创建一个 Comparer<int>
虽然.
For surrogate pairs, a Comparer<char>
isn't going to be feasible anyway, because you don't have a single char
. You could create a Comparer<int>
though.
这篇关于比较 char 忽略大小写的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!