Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make String.Contains case insensitive? [duplicate]

How can I make the following case insensitive?

myString1.Contains("AbC")
like image 892
CJ7 Avatar asked Jul 10 '13 06:07

CJ7


People also ask

Does == ignore case?

Java String: equalsIgnoreCase() MethodTwo strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.

How do you compare two strings to ignore cases?

The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

Is TreeMap Case Insensitive?

Also, TreeMap uses a Comparator to find if an inserted key is a duplicate or a new one. Therefore, if we provide a case-insensitive String Comparator, we'll get a case-insensitive TreeMap. which we can supply in the constructor: Map<String, Integer> treeMap = new TreeMap<>(String.

Is contains case sensitive in C#?

Contains() method in C# is case sensitive. And there is not StringComparison parameter available similar to Equals() method, which helps to compare case insensitive.


3 Answers

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);
like image 199
Tobia Zambon Avatar answered Oct 17 '22 01:10

Tobia Zambon


You can use:

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

This works with any .NET version.

like image 51
joe Avatar answered Oct 17 '22 01:10

joe


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

like image 12
Kamil Budziewski Avatar answered Oct 17 '22 01:10

Kamil Budziewski