Reader Level:
Articles

Compare Strings in C#

By Mahesh Chand on August 21, 2010
This code snippet shows how to trim strings in C#.
  • 1
  • 0
  • 16810

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

Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  Mahesh has been awar... Read more

COMMENT USING

Trending up