String Compare() - C# Tutorial
C# Course / Strings / String Compare()

String Compare()

BLUF: Mastering String Compare() is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: String Compare()

C# is a powerful, modern language for enterprise solutions. Discover how String Compare() enhances your development workflow in the guide below.

The Compare function in C# is employed to compare two strings in a lexicographical order and returns an integer value.

If the two strings are identical, the function will output 0. In the scenario where the first string is considered greater than the second string, the function will return 1; otherwise, it will return -1.

Example

s1==s2 returns 0
s1>s2 returns 1
s1<s2 returns -1

Signatures

Example

public static int Compare(String first, String second)
public static int Compare(String, Int32, String, Int32, Int32)
public static int Compare(String, Int32, Int32, String, Int32, Boolean) 
public static int Compare(String, Boolean, Int32, Int32, String, Int32, CultureInfo) 
public static int Compare(String, CultureInfo, Int32, Int32, String, Int32, CompareOptions) 
public static int Compare(String, Int32, Int32, String, Int32, StringComparison)
public static int Compare(String, String, Boolean) 
public static int Compare(String, String, Boolean, CultureInfo) 
public static int Compare(String, String, CultureInfo, CompareOptions)
public static int Compare(String, String, StringComparison)

Parameters

The first parameter denotes a string that will be compared with the second string.

The second argument represents a string that will be compared with the first string.

Return

It returns an integer value.

C# String Compare Method Example

Example

using System;  
    public class StringExample  
    {  
        public static void Main(string[] args)  
        {  
            string s1 = "hello";  
            string s2 = "hello";  
            string s3 = "csharp";
            string s4 = "mello";
      
            Console.WriteLine(string.Compare(s1,s2)); 
            Console.WriteLine(string.Compare(s2,s3)); 
            Console.WriteLine(string.Compare(s3,s4)); 
        }  
    }

Output:

Output

0
1
-1

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience