Ignore case and compare in C# [duplicate]

自古美人都是妖i 提交于 2019-12-05 12:32:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!