问题描述
我想知道比较两个忽略大小写的字符的正确方法适用于所有文化.另外, 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 忽略大小写的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)