Part 29. String Compare




String comparison is a common programming task, .Net provides several way to compare two String in C#. we will see different ways to compare two String in C#.
compare String and when to use equals() ,compare or compareTo() for comparison etc.

compare() :

compare method is used to compare the first string to another string. if the string value are same 0 and if string are not equal is return 1 else it return -1.


class Program

    {
        static void Main(string[] args)
        {
            string s1 = "csharptutorialpoint";
            string s2 = "chandan";
            string s3 = "csharptutorialpoint";
            Console.WriteLine(string.Compare(s1, s2));
            Console.WriteLine(string.Compare(s2, s3));
            Console.ReadLine();
        }
    }

Output

 1
-1

compareTo() :
 CompareTo() method is used compare the object and its return integer value. the value of the specified object.
  • Zero Value (0) - Both objects are equal.
  • Negative Value (-1) - An object is smaller than passing an object in lexical order.
  • Positive Value (1) - Calling object is greater than passing object in lexical order.

class  Program

    {
        static void Main(string[] args)
        {
            int s1 = 10;
            int s2 =20;
            int s3 = 4;
            int s4 = 4;
             Console.WriteLine(s1.CompareTo(s2));
             Console.WriteLine(s2.CompareTo(s3));
             Console.WriteLine(s4.CompareTo(s3));
             Console.ReadLine();
        }
    }

Output

-1
 1
 0

class Program

    {
          static void Main(string[] args)
        {
            String  s1 = "csharptutorialpoint";
            String  s2 = "chandan";
            String  s3 = "csharptutorialpoint";
            Console.WriteLine(s2.CompareTo(s3));
            Console.ReadLine();
        }
    }
Output
-1

class Program
    {
        {
        String learn = "csharp-tutorial-point.blogspot.com";
        String csharp = "csharp-tutorial-point.blogspot.com";
        // String compare example using equals
        if (learn.Equals(csharp))
        {
            Console.WriteLine("Same from Equals");
        }
        // String compare using compareTo
        if (learn.CompareTo(csharp) == 0)
        {
            Console.WriteLine("Same From CompareTo");
        }
         Console.ReadLine();
        }
    }

Output :
Same from Equals
Same From CompareTo