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.
s1==s2 returns 0
s1>s2 returns 1
s1<s2 returns -1
Signatures
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
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:
0
1
-1