String Comparison in C#

In this article we will discuss how to compare strings in C#.
  • 3872

The string class has three compare methods with several overloaded forms – Compare, CompareOrdinal, and CompareTo.

The Compare method compares two strings and returns an integer value that indicates their relative position in the sort order. The return value of Compare method can be less than zero, greater than zero or equals to zero depending on if one string comes before or after in the sort order. The Compare method has 8 overloaded forms. It is recommended to use the overloaded method with StringComparison. Check out best practices for using strings in .NET.

The following code compares two strings and return results on the System console.

 

string name = "Mahesh Chand";
string name2 = "Mojesh Chand";
int comp = string.Compare(name, name2);
if
(comp > 0)
{
    Console.WriteLine(name +" comes after " + name2);
}

else
if (comp < 0)
{
    Console.WriteLine(name + " comes before " + name2);
}

else
 
{
    Console.WriteLine(name + " and  " + name2 + " are same." );
}

The CompareOrdinal method compares two strings by evaluating the numeric values of the corresponding character in each string.

The following code compares two strings using the CompareOrdinal method and return results on the System console.

String name1 = "MAHESH";
String name2 = "mahesh";
String str;
int result;
result = String.CompareOrdinal(name1, name2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" :
"equal to"));
Console.Write("String '{0}' is ", name1);
Console.Write("{0} ", str);
Console
.WriteLine("String '{0}'.", name2);

 

The CompareTo method is an instance method. It compares a value (either a string or on object) with a string instance. Return values of this method are same as the Compare method. The following source code compares two strings.

The following code compares two strings using the CompareTo method and return results on the System console.

String name1 = "MAHESH";
String name2 = "mahesh";
String str;
int result;
result = name1.CompareTo(name2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("String '{0}' is ", name1);
Console.Write("{0} ", str);
Console
.WriteLine("String '{0}'.", name2);

 

 
Further Readings

You may also want to read these related articles.

Ask Your Question 

Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2018 DotNetHeaven. All rights reserved.