17

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

Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
PhOeNiX
  • 285
  • 1
  • 4
  • 9

7 Answers7

19

Try this:

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

Or, for contains:

if (string1.IndexOf(string2, StringComparison.CurrentCultureIgnoreCase) >= 0)
paul
  • 21,653
  • 1
  • 53
  • 54
10

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

Steve
  • 213,761
  • 22
  • 232
  • 286
6

Convert both strings to a same case, either upper or lower.

string1.ToUpper().Contains(string2.ToUpper());
Habib
  • 219,104
  • 29
  • 407
  • 436
5

Why not this:

if (string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase) >= 0)
{  
}
gethomast
  • 436
  • 1
  • 3
  • 10
0
string1.ToUpperInvariant().Contains(string2.ToUpperInvariant());
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
0

You can either convert both strings to uppercase, or use regular expressions:

using System.Text.RegularExpressions;

class Program {
    static void Main(string[] args) {
        string string1 = "TermSomething";
        string string2 = "term";
        bool test1 = string1.ToUpperInvariant().Contains(string2.ToUpperInvariant());
        bool test2 = Regex.IsMatch(string1, Regex.Escape(string2), RegexOptions.IgnoreCase);
    }
}

Note that if you use regular expressions you should escape the search string, so that special regex characters are interpreted literally.

Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
0
Regex.IsMatch(string1,string2,RegexOptions.IgnoreCase);

This returns boolean value.....

Ashish Gupta
  • 14,869
  • 20
  • 75
  • 134
Vijay
  • 1