Case insensitive ‘Contains(string)’

Explanation

In this Case insensitive ‘Contains(string)’ you can use the String.IndexOf Method and pass StringComparison.OrdinalIgnoreCase as the type of search. When you have to use:

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

And even better you have another way that is defining a new extension method for string:

public static class StringExtensions
{
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source?.IndexOf(toCheck, comp) >= 0;
    }
}

Note, that null propagation ?. is available. And if you have an older version so at that time use:

if (source == null) return false;
return source.IndexOf(toCheck, comp) >= 0;

USAGE:

string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);

 

 

Also, read How do I convert a String to an int in Java?

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *