We can compare strings with the help of CompareTo()
method in C#. You can compare a string with another string to know if it precedes, follows, or appears in the position as the other in the sort order.
An integer value is returned when the CompareTo()
method is used.
Following is the syntax of the CompareTo()
method:
public int CompareTo() (string str);
CompareTo()
method takes the following parameter:
str: This is the string you want to compare with the second string instance.
The value returned is an integer of type int32
. It returns a value less than 0
if the instances precedes str
. A 0
is returned if they are both in the same position in the sort order. It returns a value greater than 0
if str
is after the instance or the str
is null
.
In the code example below, we will create strings and compare their sort order using the CompareTo()
method:
// using System;// create compare string order classclass CompareSortOrder{// main methodstatic void Main(){// define and initialize stringsstring first = "Edpresso";string second = "is ";string third = "the";string fourth = "best";string fifth = "Edpresso";// compare stringsint a = first.CompareTo(second);int b = second.CompareTo(third);int c = third.CompareTo(fourth);int d = fourth.CompareTo(fifth);int e = fifth.CompareTo(first);// print returned values to the consoleSystem.Console.WriteLine(a); // -1System.Console.WriteLine(b); // -1System.Console.WriteLine(c); // 1System.Console.WriteLine(d); // -1System.Console.WriteLine(e); // 0}}
In the code above:
In line 24, -1
is returned because Edpresso
precedes is
in the sort order.
In line 25, is
precedes The
, and hence, -1
is returned. The same pattern goes for line 27.
In line 26, best
precedes the
. So the second string precedes the string instance, thus 1
is returned.
In line 28, 0
is returned because the first string Edpresso
and the second string Edpresso
are both on the same position in the sort order.