How to Compare Strings in C#?
Last Updated :
24 Jan, 2022
A string is a collection of characters and is used to store plain text. Unlike C or C++, a string in C# is not terminated with a null character. The maximum size of a string object depends on the internal architecture of the system. A variable declared followed by "string" is actually an object of string class.
How to instantiate a string object?
We can create an object of string class by using variable name followed by "string" keyword.
Syntax:
string myString;
We can also initialize a string object at the time of declaration.
Syntax:
string myString = "GeeksForGeeks";
This article focuses upon how we can compare strings in C#. For example, we are given three strings "GeeksforGeeks", "Geeks" and "GeeksforGeeks". Clearly first and last strings are the same. There are numerous ways to compare strings in C# out of which five ways are explained below in detail.
Method 1: Using String.Equals() method
The String class is specified in the .NET base class library. In other words, a String object is a sequential collection of System.Char objects which represent a string. The System.String class is immutable, that is once created its state we cannot make changes to it. String.Equals() method is a method of String class. This method takes two strings to be compared as parameters. It returns a logical value, true or false with the help of which we can determine whether the given strings are the same or not.
Syntax:
String.Equals(myString1, myString2)
Parameters: It takes two parameters myString1: First string and myString2: Second string
Return type: The return type of this method is Boolean. It will be true if both strings are equal and false if both strings are different
Example:
C#
// C# program to illustrate the working of
// String.Equals() method to compare two strings
using System;
class GFG{
static public void Main()
{
// Initialize a string
string myString1 = "GeeksforGeeks";
// Initialize another string
string myString2 = "Geeks";
// Initialize a string
string myString3 = "GeeksforGeeks";
// If this method returns true
// Print both string are same
if (String.Equals(myString1, myString2))
Console.WriteLine($"{myString1} and {myString2} are same.");
// If this method returns false
// Print both string are different
else
Console.WriteLine($"{myString1} and {myString2} are different.");
// If this method returns true
// Print both string are same
if (String.Equals(myString1, myString3))
Console.WriteLine($"{myString1} and {myString3} are same.");
// If this method returns false
// Print both string are different
else
Console.WriteLine($"{myString1} and {myString3} are different.");
// If this method returns true
// Print both string are same
if (String.Equals(myString2, myString3))
Console.WriteLine($"{myString2} and {myString3} are same.");
// If this method returns false
// Print both string are different
else
Console.WriteLine($"{myString2} and {myString3} are different.");
}
}
OutputGeeksforGeeks and Geeks are different.
GeeksforGeeks and GeeksforGeeks are same.
Geeks and GeeksforGeeks are different.
Method 2: Using String.Compare() method
This method is also defined under the String class. This method also takes two strings to be compared as parameters. It returns a numeric value depending upon the strings passed to the method. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method.
Syntax:
String.Compare(myString1, myString2)
Parameters: It takes two parameters myString1: First string and myString2: Second string
Return type: The return type of this method is Integer. It will be:
- Less than zero: If the first string is lexicographically smaller than the second string.
- zero: If both strings are equal.
- Greater than zero: If the first string is lexicographically greater than the second string.
Example:
C#
// C# program to illustrate the working of
// String.Compare() method to compare two strings
using System;
class GFG{
static public void Main()
{
// Initialize a string
string myString1 = "GeeksforGeeks";
// Initialize another string
string myString2 = "Geeks";
// Initialize another string
string myString3 = "GeeksforGeeks";
// If value returned by this method is equal to 0
// Print both string are same
if (String.Compare(myString1, myString2) == 0)
Console.WriteLine($"{myString1} and {myString2} are same.");
// If value returned by this method is less than 0
// Then print first string is smaller than the second string
else if(String.Compare(myString1, myString2) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString2}.");
// If value returned by the method is greater than 0
// Then print first string is greater than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString2}.");
// If value returned by this method is equal to 0
// Print both string are same
if (String.Compare(myString1, myString3) == 0)
Console.WriteLine($"{myString1} and {myString3} are same.");
// If value returned by this method is less than 0
// Then print first string is smaller than the second string
else if (String.Compare(myString1, myString3) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString3}.");
// If value returned by the method is greater than 0
// Then print first string is greater than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString3}.");
// If value returned by this method is equal to 0
// Print both string are same
if (String.Compare(myString2, myString3) == 0)
Console.WriteLine($"{myString2} and {myString3} are same.");
// If value returned by this method is less than 0
// Then print first string is smaller than the second string
else if (String.Compare(myString2, myString3) < 0)
Console.WriteLine(
$"{myString2} is lexicographically smaller than {myString3}.");
// If value returned by the method is greater than 0
// Then print first string is greater than the second string
else
Console.WriteLine(
$"{myString2} is lexicographically greater than {myString3}.");
}
}
OutputGeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
Method 3: Using CompareTo() Method
This is an instance method defined under the String class and it is applied directly to a string or a string object. It returns a numeric value depending on the strings to be compared. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method.
Syntax:
myString1.CompareTo(myString2)
Parameters: It takes one parameter that is myString2: Second string
Return type: The return type of this method is Integer. It will be:
- Less than zero: If the first string is lexicographically smaller than the second string.
- zero: If both strings are equal.
- Greater than zero: If the first string is lexicographically greater than the second string.
Example:
C#
// C# program to illustrate the working of
// CompareTo() method to compare two strings
using System;
class GFG{
static public void Main()
{
// Initialize a string
string myString1 = "GeeksforGeeks";
// Initialize another string
string myString2 = "Geeks";
// Initialize another string
string myString3 = "GeeksforGeeks";
// If value returned by this method is equal to 0
// Then display both strings are equal
if (myString1.CompareTo(myString2) == 0)
Console.WriteLine($"{myString1} and {myString2} are same.");
// If value returned by this method is less than 0
// Then print the first string is smaller than the second string
else if (myString1.CompareTo(myString2) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString2}.");
// If value returned by this method is greater than 0
// Then print the first string is greater than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString2}.");
// If value returned by this method is equal to 0
// Then print both strings are equal
if (myString1.CompareTo(myString2) == 0)
Console.WriteLine($"{myString1} and {myString3} are same.");
// If value returned by this method is less than 0
// Then print the first string is smaller than the second string
else if(myString1.CompareTo(myString2) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString3}.");
// If value returned by this method is greater than 0
// Then print the first string is greater than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString3}.");
// If value returned by this method is equal to 0
// Then display both strings are equal
if (myString1.CompareTo(myString2) == 0)
Console.WriteLine($"{myString1} and {myString2} are same.");
// If value returned by this method is less than 0
// Then print the first string is smaller than the second string
else if (myString1.CompareTo(myString2) < 0)
Console.WriteLine(
$"{myString2} is lexicographically smaller than {myString3}.");
// If value returned by this method is greater than 0
// Then print the first string is greater than the second string
else
Console.WriteLine(
$"{myString2} is lexicographically greater than {myString3}.");
}
}
OutputGeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks is lexicographically greater than GeeksforGeeks.
Geeks is lexicographically greater than GeeksforGeeks.
Method 4: Using compare() method of StringComparer class
This method is defined under the StringComparer class. We can create an object of this class with the help of which we can use Compare() method to compare two strings. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method.
Syntax:
StringComparer myComparer = StringComparer.OrdinalIgnoreCase;
myComparer.Compare(myString1, myString2);
Parameters: It takes two parameters myString1: First string and myString2: Second string
Return type: The return type of this method is Integer. It will be:
- Less than zero: If the first string is lexicographically smaller than the second string.
- zero: If both strings are equal.
- Greater than zero: If the first string is lexicographically greater than the second string.
Example:
C#
// C# program to illustrate the working of Compare() method
// of StringComparer class to compare two strings
using System;
class GFG{
static public void Main()
{
// Declare an object of class StringComparer
StringComparer myComparer = StringComparer.OrdinalIgnoreCase;
// Initialize a string
string myString1 = "GeeksforGeeks";
// Initialize another string
string myString2 = "Geeks";
// Initialize another string
string myString3 = "GeeksforGeeks";
// Compare strings using Compare method
// on the instantiated object
// If this method returns 0
// Print both strings are same
if (myComparer.Compare(myString1, myString2) == 0)
Console.WriteLine($"{myString1} and {myString2} are same.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else if (myComparer.Compare(myString1, myString2) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString2}.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString2}.");
// If this method returns 0
// Print both strings are same
if (myComparer.Compare(myString1, myString3) == 0)
Console.WriteLine($"{myString1} and {myString3} are same.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else if (myComparer.Compare(myString1, myString3) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString3}.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString3}.");
// If this method returns 0
// Print both strings are same
if (myComparer.Compare(myString2, myString3) == 0)
Console.WriteLine($"{myString2} and {myString3} are same.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else if (myComparer.Compare(myString2, myString3) < 0)
Console.WriteLine(
$"{myString2} is lexicographically smaller than {myString3}.");
// If value returned by this method is greater than 0
// Then print the first string is greater than the second string
else
Console.WriteLine(
$"{myString2} is lexicographically greater than {myString3}.");
}
}
OutputGeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
Method 5: By comparing character by character (using custom compare method)
Strings can be compared character by character. Follow the steps below to compare two strings by using a custom compare method.
- Declare a static method Compare outside of the main method. Set the return type of this method as int.
- Initialize a variable len as the minimum of the lengths of both the strings.
- Iterate over index = 0 to index = len - 1 using a for loop. At each iteration compare corresponding characters of strings.
- If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return -1.
- If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return 1.
- After the end of the for-loop, if lengths of both strings are equal then return 0. If the length of the first string is less than the second string return -1 otherwise return 1.
- Call Compare() function from the main function by passing strings to be compared as parameters. If Compare() function returns 0 then print the first string is the same as the second string. If Compare() function returns -1 then the print first string is smaller than the second string else print first string is greater than the second string.
Example:
C#
// C# program to illustrate the working of
// custom Compare() method to compare two strings
using System;
class GFG{
// Compare method to compare two strings
static public int Compare(string myString1, string myString2)
{
// len stores minimum of two string lengths
int len = Math.Min(myString1.Length, myString2.Length);
// Iterate over all characters
for(int index = 0; index < len; index++)
{
// If the first not matched character of first
// string is smaller than the second string then
// return -1
if (myString1[index] < myString2[index])
return -1;
// If the first not matched character of first
// string is greater than the second string then
// return 1
else if (myString1[index] > myString2[index])
return 1;
}
// If lengths are equal
// Return 0
if (myString1.Length == myString2.Length)
return 0;
// If length of first string is smaller than the second string
// then return -1
// If length of first string is greater than the second string
// then return 1
return ((myString1.Length < myString2.Length) ? -1 : 1);
}
// Driver code
static public void Main()
{
// Initialize a string
string myString1 = "GeeksforGeeks";
// Initialize another string
string myString2 = "Geeks";
// Initialize another string
string myString3 = "GeeksforGeeks";
// If value returned by this method is equal to 0
// Then print both strings are same
if (Compare(myString1, myString2) == 0)
Console.WriteLine($"{myString1} and {myString2} are same.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else if (Compare(myString1, myString3) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString2}.");
// If value returned by this method is greater than 0
// Then print the first string is greater than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString2}.");
// If value returned by this method is equal to 0
// Then print both strings are same
if (Compare(myString1, myString3) == 0)
Console.WriteLine($"{myString1} and {myString3} are same.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else if (Compare(myString1, myString3) < 0)
Console.WriteLine(
$"{myString1} is lexicographically smaller than {myString3}.");
// If value returned by this method is greater than 0
// Then print the first string is greater than the second string
else
Console.WriteLine(
$"{myString1} is lexicographically greater than {myString3}.");
// If value returned by this method is equal to 0
// Then print both strings are same
if (Compare(myString2, myString3) == 0)
Console.WriteLine($"{myString2} and {myString3} are same.");
// If value returned by this method is smaller than 0
// Then print the first string is smaller than the second string
else if (Compare(myString2, myString3) < 0)
Console.WriteLine(
$"{myString2} is lexicographically smaller than {myString3}.");
// If value returned by this method is greater than 0
// Then print the first string is greater than the second string
else
Console.WriteLine(
$"{myString2} is lexicographically greater than {myString3}.");
}
}
OutputGeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
Similar Reads
Int16.CompareTo() Method in C#
Int16.CompareTo Method is used to compare the current instance to a specified object or another Int16 instance. It returns an integer which shows whether the value of the current instance is less than, equal to, or greater than the value of the specified object or the other Int16 instance. There are
4 min read
C# | StringComparer.Compare Method
In C#, the Compare method is used to compare two objects or strings and returns an indication of their relative sort order.Example: C# program to illustrate how to use StringComparer() to perform ordinal comparison.C#// C# program to illustrate the // CompareOrdinal(String, Int32, // String, Int32,
3 min read
How to compare two ValueTuple in C#?
To compare two instances of ValueTuple you can use CompareTo method which is provided by ValueTuple structure. ValueTuple.CompareTo(ValueTuple) Method is used to compare the current instance of ValueTuple with another ValueTuple instance. It always returns zero if they are equal to each other. Synta
2 min read
SQL Query to Compare Two Strings
SQL stands for Structured Query Language. It is used to communicate with the database. There are some standard SQL commands like 'select', 'delete', 'alter' etc. To compare two strings in SQL Server, there is no direct way. In this article, we will learn how to compare two strings in an MS SQL serve
2 min read
C# String CompareOrdinal() Method
In C#, CompareOrdinal() is a method of the String class. This method is used to compare the two specified string objects or substrings using the numerical values (Unicode) of the corresponding Char objects in each string or substring. It performs a case-sensitive and culture-insensitive comparison.O
4 min read
C# | How to copy a String into another String
String.Copy(String) Method is used to create a new instance of String with the same value as a specified String. In other words, this method is used to copy the data of one string into a new string. The new string contains same data like an original string but represents a different object reference
2 min read
How to compare Enum values in C#?
Enum.CompareTo(Object) Method is used to compare the current instance to a specified object and returns an indication of their relative values. Syntax: public int CompareTo (object target); Here, the target is an object to compare or it may be null. Returns: This method returns a signed number which
2 min read
File Comparison Using C#
C# is a general-purpose, modern and object-oriented programming language pronounced as âC Sharpâ, in which we can create files. Sometimes we need to do perform operations the on file. This operation can be anything from comparing files byte by byte or needing to check the dates or length of files. F
2 min read
C# String ToLower() Method
In C#, the ToLower() method is a string method used to convert all uppercase characters in a string to lowercase. If a character does not have a lowercase equivalent, such as a special symbol, it remains unchanged. This method is particularly useful when performing case-insensitive string comparison
3 min read
How to read or input a string?
In this article, we are going to learn how to print or output a string using different languages. Strings are considered a data type in general and are typically represented as arrays of bytes (or words) that store a sequence of characters. Strings are defined as an array of characters. Topics: How
3 min read