问题
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())
回答1:
use this:
var result = String.Compare("AA", "aa", StringComparison.OrdinalIgnoreCase);
String.Compare Method (String, String, Boolean)
回答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.
回答3:
Well, you can use String.Equals(String,StringComparison)
method. Just pass it StringComparison.InvariantCultureIgnoreCase
or StringComparison.CurrentCultureIgnoreCase
depending on your objectives...
回答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)
回答5:
txt_SecAns.Trim().Compare(hidden_secans.Trim(), StringComparison.CurrentCultureIgnoreCase)
回答6:
string.Compare(string1, string2, true) == 0 will compare if the two strings are equal ignoring case
回答7:
Use StringComparison.CurrentCultureIgnoreCase
:
if (txt_SecAns.Text.Trim().Equals(hidden_secans.Value.ToString(), StringComparison.CurrentCultureIgnoreCase))
回答8:
String.Compare(str1, str2, true);
回答9:
Just like this:
if (string.Compare(txt_SecAns.Text.Trim(), hidden_secans.Value.ToString(), true) == 0)
{
// DoSomething
}
The third parameter true
tells string.Compare to ignore case.
回答10:
I would personaly compare with a proper culture like everyone here, but something hasn't been suggested :
public bool CompareStrings(string stringA, string StringB)
{
return stringA.ToLower() == stringB.ToLower();
}
来源:https://stackoverflow.com/questions/8243273/ignore-case-and-compare-in-c-sharp