Ignore case and compare in C#

51,687

Solution 1

use this:

var result = String.Compare("AA", "aa", StringComparison.OrdinalIgnoreCase);

String.Compare Method (String, String, Boolean)

Solution 2

Case-insensitive string comparison is done like this in C#:

string.Equals("stringa", "stringb", StringComparison.CurrentCultureIgnoreCase)

Watch out! this code is culture dependant; there are several other options available, see http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx.

Solution 3

Well, you can use String.Equals(String,StringComparison) method. Just pass it StringComparison.InvariantCultureIgnoreCase or StringComparison.CurrentCultureIgnoreCase depending on your objectives...

Solution 4

From MSDN:

String.Compare Method (String, String, Boolean):

public static int Compare(
    string strA,
    string strB,
    bool ignoreCase
)

so in your case:

if( String.Compare(txt_SecAns.Text.Trim(), hidden_secans.Value, true) == 0) 

Solution 5

Use StringComparison.CurrentCultureIgnoreCase:

if (txt_SecAns.Text.Trim().Equals(hidden_secans.Value.ToString(), StringComparison.CurrentCultureIgnoreCase))
Share:
51,687

Related videos on Youtube

Murthy
Author by

Murthy

Updated on July 09, 2022

Comments

  • Murthy
    Murthy 11 months

    How to convert the string to uppercase before performing a compare, or is it possible to compare the string by ignoring the case

     if (Convert.ToString(txt_SecAns.Text.Trim()).ToUpper() == 
         Convert.ToString(hidden_secans.Value).ToUpper())
    
  • CodesInChaos
    CodesInChaos over 11 years
    Using the Turkish culture this code can return false for STRINGA and stringa. It's very well possible that the OP wants that, but it's important to be aware that culture influences case insensitive comparisons
  • CodesInChaos
    CodesInChaos over 11 years
    I'd prefer a method that explicitly specifies the culture. It's not obvious that this uses the current culture.
  • CodesInChaos
    CodesInChaos over 11 years
    I think the results from this can still differ from using a case insensitive comparer with the same culture.
  • Tudor
    Tudor over 11 years
    Yes, this version uses the current culture according to MSDN. There is an overload with a fourth parameter that lets you specify the culture explicitly.
  • Fischermaen over 11 years
    If you want it to be culture invariant than use this string.Equals("stringa", "stringb", StringComparison.InvariantCultureIgnoreCase)
  • CodesInChaos
    CodesInChaos over 11 years
    "I".ToLower()!="i".ToLower() On a Turkish system.
  • Tipx
    Tipx over 11 years
    Oh, wow. I didn't expect that! Well, I think I'll stick with my non-Turkish mindset! ;-)
  • PatPeter
    PatPeter over 4 years
    What's the difference between this and StringComparison.OrdinalIgnoreCase?

Related