How to compare strings in a Sort Order C#
Overview
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.
Syntax
Following is the syntax of the CompareTo() method:
public int CompareTo() (string str);
Parameters
CompareTo() method takes the following parameter:
str: This is the string you want to compare with the second string instance.
Return value
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.
Code example
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,
-1is returned becauseEdpressoprecedesisin the sort order. -
In line 25,
isprecedesThe, and hence,-1is returned. The same pattern goes for line 27. -
In line 26,
bestprecedesthe. So the second string precedes the string instance, thus1is returned. -
In line 28,
0is returned because the first stringEdpressoand the second stringEdpressoare both on the same position in the sort order.