Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
compare
string
communitycreator

How to compare strings in a Sort Order C#

Theodore Kelechukwu Onyejiaku

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 class
class CompareSortOrder
{
    // main method
    static void Main()
    {
      // define and initialize strings
      string first = "Edpresso";
      string second = "is ";
      string third = "the";
      string fourth = "best";
      string fifth = "Edpresso";

      // compare strings
      int 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 console
      System.Console.WriteLine(a);    // -1
      System.Console.WriteLine(b);    // -1
      System.Console.WriteLine(c);    // 1
      System.Console.WriteLine(d);    // -1
      System.Console.WriteLine(e);    // 0
    }
}

In the code above:

  1. In line 24, -1 is returned because Edpresso precedes is in the sort order.

  2. In line 25, is precedes The, and hence, -1 is returned. The same pattern goes for line 27.

  3. In line 26, best precedes the. So the second string precedes the string instance, thus 1 is returned.

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

RELATED TAGS

c#
compare
string
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring