How to Compare Strings in C#

In this post we will learn about “How to compare strings in C#”. C# has one inbuild method named String.Compare() which is used to compare first string with second string. As an output it returns an integer value. Following out will be there in different scenarios.

  • If both strings are equal, it returns 0.
  • If first string is greater than second string, then it will return 1.
  • If first string is smaller than second string, then it will return -1.

public static int Compare (String first, String second)  

In general compare method accept two arguments and explanation of these arguments are as:

First Parameter: first argument represents string which is to be compared with second string.

Second Parameters: second argument represents string which is to be compared with first string.

using System;    
    public class StringCompare    
    {    
        public static void Main(string[] args)    
        {    
            string n1 = "Rakesh";    
            string n2 = "Rakesh";    
            string n3 = "code";  
            string n4 = "config";  
        
            Console.WriteLine(string.Compare(n1,n2));   
            Console.WriteLine(string.Compare(n2,n3));   
            Console.WriteLine(string.Compare(n3,n4)); 
            Console.WriteLine(string.Compare(n1,n4));    
        }    
    }  

It is pretty simple example; I will wait to see its output in comments section of this article. Please write what will be the output of above program.

Using String.Equals() method

Apart from above compare method we can also use String.Equals() method to do string comparison. String.Equals() method is a method of String class. This method takes two strings to be compared as parameters.

Syntex:

String.Equals(name1, name2)

Code sample of String.Equals():

static public void Main()
{
     string name1 = "CodeConfig";  
     string name2 = "CodeConfig";
  
      if (String.Equals(name1, name2))  
       {
          Console.WriteLine($"{name1} and {name2} are same."); 
       }
   else
      {
         Console.WriteLine($"{name1} and {name2} are NOT same."); 
      } 
}

Case sensitive String Comparision

There is one another way to use Equals () method which does case sensitive comparison, is given below:

string name1 = "CodeConfig";
string name2 = "CodeConfig";

bool result = name1.Equals(name2);

In above comparison we will compare two strings. This method will compare the binary value of each Char object in two strings. As a result, the default ordinal comparison is also case-sensitive.

You can check more on this here and can Visit our website’s C# Section for more such information.

You may like

Leave a Reply

Your email address will not be published. Required fields are marked *