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))
Related videos on Youtube
Author by
Murthy
Updated on July 09, 2022Comments
-
Murthy 11 monthsHow 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 over 11 yearsUsing the Turkish culture this code can return false forSTRINGAandstringa. It's very well possible that the OP wants that, but it's important to be aware that culture influences case insensitive comparisons -
CodesInChaos over 11 yearsI'd prefer a method that explicitly specifies the culture. It's not obvious that this uses the current culture. -
CodesInChaos over 11 yearsI think the results from this can still differ from using a case insensitive comparer with the same culture. -
Tudor over 11 yearsYes, 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 yearsIf you want it to be culture invariant than use this
string.Equals("stringa", "stringb", StringComparison.InvariantCultureIgnoreCase) -
CodesInChaos over 11 years"I".ToLower()!="i".ToLower()On a Turkish system. -
Tipx over 11 yearsOh, wow. I didn't expect that! Well, I think I'll stick with my non-Turkish mindset! ;-) -
PatPeter over 4 yearsWhat's the difference between this andStringComparison.OrdinalIgnoreCase?