Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitive comparison in C# [duplicate]

I am comparing two strings using following code

string1.Contains(string2)

but i am not getting results for case insensitive search. Moreover I cant use String.Compare coz i dont want to match the whole name as the name is very big. My need is to have case insensitive search and the search text can be of any length which the String1 contains.

Eg Term************** is the name. I enter "erm" in textbox den i get the result. but when i enter "term" i dont get any result. Can anyone help me :)

like image 313
PhOeNiX Avatar asked May 29 '12 10:05

PhOeNiX


People also ask

What is case-insensitive comparison?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters.

What is case-insensitive in C?

C Program Case Insensitive String Comparison USING stricmp() built-in string function. /* C program to input two strings and check whether both strings are the same (equal) or not using stricmp() predefined function. stricmp() gives a case insensitive comparison.

Is string compare case-sensitive C?

It is case-insensitive.

How do you perform a case-insensitive comparison of two strings?

The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.


2 Answers

Try this:

string.Equals("this will return true", "ThIs WiLL ReTurN TRue", StringComparison.CurrentCultureIgnoreCase)

Or, for contains:

if (string1.IndexOf(string2, StringComparison.CurrentCultureIgnoreCase) >= 0)
like image 166
paul Avatar answered Sep 21 '22 01:09

paul


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

like image 36
Steve Avatar answered Sep 19 '22 01:09

Steve