C# String Compare Method Example

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

The C# Compare() method is used to compare the first string with the second string lexicographically. It returns an integer value.

Rules

  • s1==s2 returns 0
  • s1>s2 returns 1
  • s1<s2 returns -1
If both strings are equal then it returns 0. If the first string is greater than the second string, it returns 1 else it returns -1.

C# String Compare Method Example

using System;

public class StringDemo
{
    public static void Main(string[] args)
    {
        string s1 = "sourcecodeexamples";    
        string s2 = "sourcecodeexamples";    
        string s3 = "coding";  
        string s4 = "coding1";  
        
        Console.WriteLine(string.Compare(s1,s2));   
        Console.WriteLine(string.Compare(s2,s3));   
        Console.WriteLine(string.Compare(s3,s4));      

    }
}

Output:

0
1
-1

Related C# String Examples

References


Comments