Case-insensitive substring search (C#)

August 18th, 2007    1 Comment

Problem:

You want to do an IndexOf search to check whether searchString occurs in chunkOfText. You want the match to be case-insensitive, but you don't want to have to convert both stings to lower case or upper case before doing the comparison because it slows things down.

Answer (in .NET):

Use the CompareInfo class from System.Globalization.

How to do it:

Add using System.Globalization; at the top of your code.

Then you can do something like

int searchResultInt = CultureInfo.CurrentUICulture.CompareInfo.IndexOf(chunkOfText, searchString, CompareOptions.IgnoreCase);

Where chunkOfText is the string you want to search through and searchString is the string you're looking for - that is, the substring. As with a normal IndexOf, this returns -1 if there's no match, or the index of the first character if a match is found.

Comments

  1. User Gravatar Noel said:

    October 16th, 2011 at 2:41 am (#)

    You can just use

    int searchResultInt = chunkOfText.IndexOf(searchString,, StringComparison.CurrentCultureIgnoreCase)

Leave a comment