Compare Strings in C#

Comparing Strings

The Compare method compares two strings and returns an integer value. The return value of Compare method can be less than zero, greater than zero or equals to zero.

Value Meaning
Less than zero When first string is less than second.
Zero When both strings are equal.
Greater than zero When first string is greater than zero.

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

// Comparing two strings
//====================================
string str1 = "ppp";
string str2 = "ccc";
int res = String.Compare(str1, str2);
Console.WriteLine("First result:" +res.ToString());
str2 = "ttt"; res = String.Compare(str1, str2);
Console.WriteLine("Second result:" +res.ToString());
str1 = "ttt"; res = String.Compare(str1, str2);
Console.WriteLine("Third result:" +res.ToString));
//====================================

TheCompareTo 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.

// CompareTo Method
string str = "kkk";
Console.WriteLine( str.CompareTo(str1) );


Read
C# Strings  to learn more about strings in C#.

Up Next
    Ebook Download
    View all
    Learn
    View all