C# String CompareTo Method Example

In this source code example, we will demonstrate the usage of String.CompareTo() method in C# with an example.

The C# CompareTo() method is used to compare a String instance with a specified String object. It indicates whether this String instance precedes, follows, or appears in the same position in the sort order as the specified string or not.

C# String CompareTo Method Example

The following example uses the CompareTo method to compare the current string instance with another string.
using System;

public class StringDemo
{
    public static void Main(string[] args)
    {
        string strFirst = "Goodbye";
        string strSecond = "Hello";
        string strThird = "a small string";
        string strFourth = "goodbye";
        
        // Compare a string to itself.
        Console.WriteLine(CompareStrings(strFirst, strFirst));
        
        Console.WriteLine(CompareStrings(strFirst, strSecond));
        Console.WriteLine(CompareStrings(strFirst, strThird));
        
        // Compare a string to another string that varies only by case.
        Console.WriteLine(CompareStrings(strFirst, strFourth));
        Console.WriteLine(CompareStrings(strFourth, strFirst));     

    }
    
    private static string CompareStrings( string str1, string str2 )
   {
      // Compare the values, using the CompareTo method on the first string.
      int cmpVal = str1.CompareTo(str2);

       if (cmpVal == 0) // The strings are the same.
         return "The strings occur in the same position in the sort order.";
      else if (cmpVal < 0)
         return "The first string precedes the second in the sort order.";
      else
         return "The first string follows the second in the sort order.";
    }
}

Output:

The strings occur in the same position in the sort order.
The first string precedes the second in the sort order.
The first string follows the second in the sort order.
The first string follows the second in the sort order.
The first string precedes the second in the sort order.

Related C# String Examples

References

https://docs.microsoft.com/en-us/dotnet/api/system.string.compareto?view=net-6.0


Comments