Case Insensitive comparison in C#
This question already has an answer here:
string.Equals("this will return true", "ThIs WiLL ReTurN TRue", StringComparison.CurrentCultureIgnoreCase)
或者,包含
if (string1.IndexOf(string2, StringComparison.CurrentCultureIgnoreCase) >= 0)
I prefer an extension method like this.
public static class StringExtensions
{
public static bool Contains(this string source, string value, StringComparison compareMode)
{
if (string.IsNullOrEmpty(source))
return false;
return source.IndexOf(value, compareMode) >= 0;
}
}
Notice that in this way you could avoid the costly transformation in upper or lower case.
You could call the extension using this syntax
bool result = "This is a try".Contains("TRY", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(result);
Please note: the above extension (as true for every extension method) should be defined inside a non-nested, non-generic static class See MSDN Ref
为什么不这样做:
if (string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase) >= 0) { }链接地址: http://www.djcxy.com/p/13084.html
上一篇: 不敏感的StringA.Contains(StringB)?
下一篇: 在C#中不区分大小写的比较