简体   繁体   English

是否有 C# 不区分大小写的等于运算符?

[英]Is there a C# case insensitive equals operator?

I know that the following is case sensitive:我知道以下内容区分大小写:

if (StringA == StringB) {

So is there an operator which will compare two strings in an insensitive manner?那么是否有一个运算符会以不敏感的方式比较两个字符串?

Try this:尝试这个:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);

The best way to compare 2 strings ignoring the case of the letters is to use the String.Equals static method specifying an ordinal ignore case string comparison.比较忽略字母大小写的 2 个字符串的最佳方法是使用String.Equals static 方法指定序数忽略大小写字符串比较。 This is also the fastest way, much faster than converting the strings to lower or upper case and comparing them after that.这也是最快的方法,比将字符串转换为小写或大写并在此之后进行比较要快得多。

I tested the performance of both approaches and the ordinal ignore case string comparison was more than 9 times faster .我测试了这两种方法的性能,顺序忽略大小写字符串比较快了 9 倍以上 It is also more reliable than converting strings to lower or upper case (check out the Turkish i problem).它也比将字符串转换为小写或大写更可靠(查看土耳其语 i 问题)。 So always use the String.Equals method to compare strings for equality:所以总是使用String.Equals方法来比较字符串是否相等:

String.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);

If you want to perform a culture specific string comparison you can use the following code:如果要执行特定于文化的字符串比较,可以使用以下代码:

String.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase);

Please note that the second example uses the the string comparison logic of the current culture, which makes it slower than the "ordinal ignore case" comparison in the first example, so if you don't need any culture specific string comparison logic and you are after maximum performance, use the "ordinal ignore case" comparison.请注意,第二个示例使用当前文化的字符串比较逻辑,这使得它比第一个示例中的“序数忽略大小写”比较慢,所以如果您不需要任何文化特定的字符串比较逻辑并且您是达到最佳性能后,使用“序数忽略大小写”比较。

For more information, read the full story on my blog .有关更多信息,请阅读我的博客上的完整故事

There are a number of properties on the StringComparer static class that return comparers for any type of case-sensitivity you might want: StringComparer static class 上有许多属性可以返回您可能需要的任何类型的区分大小写的比较器:

StringComparer Properties StringComparer属性

For instance, you can call例如,您可以调用

StringComparer.CurrentCultureIgnoreCase.Equals(string1, string2)

or或者

StringComparer.CurrentCultureIgnoreCase.Compare(string1, string2)

It's a bit cleaner than the string.Equals or string.Compare overloads that take aStringComparison argument.它比采用StringComparison参数的string.Equalsstring.Compare重载要干净一些。

System.Collections.CaseInsensitiveComparer

or或者

System.StringComparer.OrdinalIgnoreCase
string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

or或者

if (StringA.Equals(StringB, StringComparison.CurrentCultureIgnoreCase)) {

but you need to be sure that StringA is not null.但您需要确保 StringA 不是 null。 So probably better tu use:所以可能更好的你使用:

string.Equals(StringA , StringB, StringComparison.CurrentCultureIgnoreCase);

as John suggested正如约翰建议的那样

EDIT: corrected the bug编辑:更正了错误

Here an idea to simplify the syntax:这里有一个简化语法的想法:

public class IgnoreCase
{
    private readonly string _value;

    public IgnoreCase(string s)
    {
        _value = s;
    }

    protected bool Equals(IgnoreCase other)
    {
        return this == other;
    }

    public override bool Equals(object obj)
    {
        return obj != null &&
               (ReferenceEquals(this, obj) || (obj.GetType() == GetType() && this == (IgnoreCase) obj));
    }

    public override int GetHashCode()
    {
        return _value?.GetHashCode() ?? 0;
    }

    public static bool operator ==(IgnoreCase a, IgnoreCase b)
    {
        return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
    }

    public static bool operator !=(IgnoreCase a, IgnoreCase b)
    {
        return !(a == b);
    }

    public static implicit operator string(IgnoreCase s)
    {
        return s._value;
    }

    public static implicit operator IgnoreCase(string s)
    {
        return new IgnoreCase(s);
    }
}

Usable like:可用如:

Console.WriteLine((IgnoreCase) "a" == "b"); // false
Console.WriteLine((IgnoreCase) "abc" == "abC"); // true
Console.WriteLine((IgnoreCase) "Abc" == "aBc"); // true
Console.WriteLine((IgnoreCase) "ABC" == "ABC"); // true

You can use您可以使用

if (stringA.equals(StringB, StringComparison.CurrentCultureIgnoreCase))

Operator?操作员? NO, but I think you can change your culture so that string comparison is not case-sensitive.不,但我认为您可以更改您的文化,以便字符串比较不区分大小写。

// you'll want to change this...
System.Threading.Thread.CurrentThread.CurrentCulture
// and you'll want to custimize this
System.Globalization.CultureInfo.CompareInfo

I'm confident that it will change the way that strings are being compared by the equals operator.我相信它会改变 equals 运算符比较字符串的方式。

I am so used to typing at the end of these comparison methods: , StringComparison.我很习惯在这些比较方法的末尾键入: , StringComparison.

So I made an extension.所以我做了一个扩展。

namespace System
{   public static class StringExtension
    {
        public static bool Equals(this string thisString, string compareString,
             StringComparison stringComparison)
        {
            return string.Equals(thisString, compareString, stringComparison);
        }
    }
}

Just note that you will need to check for null on thisString prior to calling the ext.请注意,在调用分机之前,您需要检查 thisString 上的thisString

Others answer are totally valid here, but somehow it takes some time to type StringComparison.OrdinalIgnoreCase and also using String.Compare .其他答案在这里完全有效,但不知何故,键入StringComparison.OrdinalIgnoreCase并使用String.Compare需要一些时间。

I've coded simple String extension method, where you could specify if comparison is case sensitive or case senseless with boolean - see following answer:我编写了简单的字符串扩展方法,您可以在其中使用 boolean 指定比较是区分大小写还是不区分大小写 - 请参见以下答案:

https://stackoverflow.com/a/49208128/2338477 https://stackoverflow.com/a/49208128/2338477

Just do做就是了

if (stringA.toLower() == stringB) {};

Then write StringB as a lowercase, to do stringB.toLower() as well.然后将 StringB 写为小写,也可以执行stringB.toLower()

.toLower() returns a copy of the string as lowercase and therefore will not alter the original string. .toLower()以小写形式返回字符串的副本,因此不会更改原始字符串。

if (StringA.ToUpperInvariant() == StringB.ToUpperInvariant()) {

People report ToUpperInvariant() is faster than ToLowerInvariant().人们报告 ToUpperInvariant() 比 ToLowerInvariant() 快。

string.Compare(string1, string2, true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM