How to Make String.Contains Case Insensitive?

Views: 1026
Comments: 1
Like/Unlike: 1
Posted On: 21-Sep-2017 04:48 

Share:   fb twitter linkedin
Brian
Moderator
2232 Points
14 Posts

Introduction

String.Contains Method returns a value indicating whether a specified substring occurs within this string. This method do an ordinal (case-sensitive and culture-insensitive) comparison. The search starts at the first character position of this string and continues through the last character position.

Description

To determine whether a string contains a specified substring by using something other than ordinal comparison (such as culture-sensitive comparison, or ordinal case-insensitive comparison), we can create a custom extension method. The following example defines a String extension method that includes a StringComparison parameter and indicates whether a string contains a substring when using the specified form of string comparison.

using System;

public static class MyStringExtensions
{
   public static bool Contains(this String str, String substring,
                               StringComparison comp)
   {                            
      if (substring == null)
         throw new ArgumentNullException("substring",
                                         "substring cannot be null.");
      else if (! Enum.IsDefined(typeof(StringComparison), comp))
         throw new ArgumentException("comp is not a member of StringComparison",
                                     "comp");

      return str.IndexOf(substring, comp) >= 0;                      
   }
}

WE can use it as follows:

using System;

public class MyExample
{
   public static void Main()
   {
      String s = "This is a nice string.";
      String sub1 = "this";
      Console.WriteLine("Does '{0}' contain '{1}'?", s, sub1);
      StringComparison comp = StringComparison.Ordinal;
      Console.WriteLine("   {0:G}: {1}", comp, s.Contains(sub1, comp));

      comp = StringComparison.OrdinalIgnoreCase;
      Console.WriteLine("   {0:G}: {1}", comp, s.Contains(sub1, comp));
   }
}

Output:

// The example displays the following output:
//       Does 'This is a string.' contain 'this'?
//          Ordinal: False
//          OrdinalIgnoreCase: True

Reference

https://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

Conlusion

We will see how to make extension method to so that String.Contains can accept other StringComparision options. Hope it will helpful.

1 Comments
good one ....

Smith
04-Oct-2017 at 01:37
 Log In to Chat