C# 比较字符忽略大小写的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1394877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:02:22  来源:igfitidea点击:

What is the correct way to compare char ignoring case?

c#.netstringcomparisonchar

提问by Brett Ryan

I'm wondering what the correct way to compare two characters ignoring case that will work for all cultures. Also, is Comparer<char>.Defaultthe best way to test two characters without ignoring case? Does this work for surrogate-pairs?

我想知道比较两个字符的正确方法是什么,忽略适用于所有文化的大小写。另外,是Comparer<char>.Default在不忽略大小写的情况下测试两个字符的最佳方法吗?这对代理对有效吗?

EDIT: Added sample IComparer<char>implementation

编辑:添加示例IComparer<char>实现

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()));

采纳答案by Jon Skeet

It depends on what you mean by "work for all cultures". Would you want "i" and "I" to be equal even in Turkey?

这取决于您所说的“为所有文化工作”是什么意思。即使在土耳其,您也希望“我”和“我”平等吗?

You could use:

你可以使用:

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);

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.

对于代理对, aComparer<char>无论如何都不可行,因为您没有单个char. 你可以创建一个Comparer<int>虽然。

回答by Sergio

string.Compare("string a","STRING A",true)

string.Compare("string a","STRING A",true)

It will work for every string

它适用于每个字符串

回答by Henk Holterman

Using the default (that is notthe invariant) culture:

使用默认(不是不变的)文化:

if (char.ToLower(ch1) == char.ToLower(ch2))
{  ....  }

Or specify a culture:

或者指定一种文化:

CultureInfo myCulture = ...;
if (char.ToLower(ch1, myCulture) == char.ToLower(ch2, myCulture))
{  ....  }

回答by Jon Grant

As I understand it, there isn't really a way that will "work for all cultures". Either you want to compare characters for some kind of internal, non-displayed-to-the-user reason (in which case you should use the InvariantCulture), or you want to use the CurrentCulture of the user. Obviously, using the user's current culture will mean that you will get different results in different locales, but they will be consistent with what your users in those locales will expect.

据我了解,没有真正的方法可以“适用于所有文化”。要么您想出于某种内部的、非向用户显示的原因(在这种情况下您应该使用 InvariantCulture)来比较字符,要么您想使用用户的 CurrentCulture。显然,使用用户当前的文化意味着您将在不同的语言环境中获得不同的结果,但它们将与您在这些语言环境中的用户期望的结果一致。

Without knowing more about WHY you are comparing two characters, I can't really advise you on which one you should be using.

如果不了解更多关于为什么要比较两个字符的信息,我无法真正建议您应该使用哪个字符。

回答by ahawker

You could try:

你可以试试:

    class Test{
    static int Compare(char t, char p){
        return string.Compare(t.ToString(), p.ToString(), StringComparison.CurrentCultureIgnoreCase);
    }
}

But I doubt this is the "optimal" way to do it, but I'm not all of the cases you need to be checking...

但我怀疑这是做到这一点的“最佳”方式,但我并不是您需要检查的所有情况......

回答by Brett Ryan

What I was thinking that would be available within the runtime is something like the following

我认为在运行时可用的内容类似于以下内容

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()));

回答by David R Tribble

I would recommend comparing uppercase, and if they don't match then comparing lowercase, just in case the locale's uppercasing and lowercasing logic behave slightly different.

我建议比较大写,如果它们不匹配,则比较小写,以防语言环境的大写和小写逻辑的行为略有不同。

Addendum

附录

For example,

例如,

int CompareChar(char c1, char c2)
{
    int  dif;

    dif = char.ToUpper(c1) - char.ToUpper(c2);
    if (diff != 0)
        dif = char.ToLower(c1) - char.ToLower(c2);
    return dif;
}

回答by rushi parikh

You can provide last argument as true for caseInsensetive match

您可以为 caseInsensetive 匹配提供最后一个参数为真

string.Compare(lowerCase, upperCase, true);