C# 如何使 String.Contains 不区分大小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17563929/
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-10 09:50:51  来源:igfitidea点击:

How to make String.Contains case insensitive?

c#.netvb.netstringcase-insensitive

提问by CJ7

How can I make the following case insensitive?

如何使以下不区分大小写?

myString1.Contains("AbC")

回答by Kamil Budziewski

bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);

[EDIT] extension code:

[编辑] 扩展代码:

public static bool Contains(this string source, string cont
                                                    , StringComparison compare)
{
    return source.IndexOf(cont, compare) >= 0;
}

This could work :)

这可以工作:)

回答by joe

You can use:

您可以使用:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

这适用于任何 .NET 版本。

回答by Tobia Zambon

You can create your own extension method to do this:

您可以创建自己的扩展方法来执行此操作:

public static bool Contains(this string source, string toCheck, StringComparison comp)
  {
    return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
  }

And then call:

然后调用:

 mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);