How to Compare Strings in C#? - GeeksforGeeks

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.
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.
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 stringsusing 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.");           }}
GeeksforGeeks and Geeks are different.
GeeksforGeeks and GeeksforGeeks are same.
Geeks and GeeksforGeeks are different.
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 stringsusing 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}.");  }}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
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 stringsusing 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}.");  }}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks is lexicographically greater than GeeksforGeeks.
Geeks is lexicographically greater than GeeksforGeeks.
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 stringsusing 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}.");  }}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
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.
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 stringsstatic 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 codestatic 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}.");}}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
sweetyty
simmytarika5
CSharp-string
CSharp-Strings-Programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Partial Classes in C#
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#