Home »
C#.Net
String.Compare() method with example in C#
C# String.Compare() method: Here, we are going to learn about the Compare() method of String class with example.
Submitted by IncludeHelp, on March 17, 2019
C# String.Compare() Method
String.Compare() method is used to compare two string objects, it returns values 0, less than 0 or greater than 0 based on the difference of first dissimilar characters.
Syntax:
int String.Compare(String1, String2);
Parameter: It accepts two strings to compare.
Return value: It returns an int value – which may 0, less than 0 or greater than 0.
Example:
Input:
string str1 = "IncludeHelp";
string str2 = "IncludeHelp";
Function call:
String.Compare(str1, str2)
Output:
0
C# Example to compare two strings using String.Compare() method
using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//string variables
string str1 = "IncludeHelp";
string str2 = "IncludeHelp";
Console.WriteLine(String.Compare("ABCD", "ABCD"));
Console.WriteLine(String.Compare("ABCD", "abcd"));
Console.WriteLine(String.Compare("abcd", "ABCD"));
//checking the condition
if (String.Compare(str1, str2)==0)
Console.WriteLine(str1 + " and " + str2 + " are same");
else
Console.WriteLine(str1 + " and " + str2 + " are not same");
str1 = "INCLUDEHELP";
str2 = "IncludeHelp";
if (String.Compare(str1, str2) == 0)
Console.WriteLine(str1 + " and " + str2 + " are same");
else
Console.WriteLine(str1 + " and " + str2 + " are not same");
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
0
1
-1
IncludeHelp and IncludeHelp are same
INCLUDEHELP and IncludeHelp are not same
Reference: String.Compare Method