ProAnswers.org

Case insensitive contains in C#?

Is there a way to make the following return true?

string title = “ASTRINGTOTEST”;
title.Contains(“string”);

There doesn’t seem to be an overload that allows me to set the case sensitivity…
Currently I UPPERCASE them both, but that’s just silly.

You could use IndexOf() and pass StringComparison.OrdinalIgnoreCase

string title = "STRING"; 
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;

Even better is defining a new extension method for string

public static bool Contains(this string source, string toCheck, StringComparison comp) { 
  return source.IndexOf(toCheck, comp) >= 0; 
} 
 
string title = "STRING"; 
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);