So what is String.Compare()? It is a built-in function in C# that used to compare 2 strings.
Take a look at its parameter:
String.Compare(string strA, string strB, bool ignoreCase)
strA
This is your first string.
strB
This is your second string.
ignoreCase
Mark true if you want to ignore the casing, false if otherwise.
So speaking of its advantage, for example, comparing string in an if-else statement.
struct StringCompareExample
{
static void Main(string[] args)
{
string strA = "Eric";
// instead of using this kind of comparison
if(strA == "Eric".ToUpper())
{
Console.Writeline("Equal");
}
else
{
Console.Writeline("Not Equal");
}
// use this
// Noticed that, it can also be useful if you are trying to ignore cases
// between strings.
if(!Convert.ToBoolean(String.Compare(strA, strB, true)))
{
Console.Writeline("Equal");
}
else
{
Console.Writeline("Not Equal");
}
Console.ReadKey();
}}
No comments:
Post a Comment