String.Compare() method with example in C#

C# String.Compare() strategy: Here, we will find out about the Compare() technique for String class with example.

C# String.Compare() Method

String.Compare() technique is utilized to analyze two string objects, it returns values 0, under 0 or more prominent than 0 dependent on the distinction of first disparate characters.

Syntax:

    int String.Clone(String1, String2);

Parameter: It acknowledges two strings to analyze.

Return value: It restores an int value – which may 0, under 0 or more prominent than 0.

Example:

    Input:
    string str1 = "JustTechReview";
    string str2 = "JustTechReview";
    
    Function call:
    String.Compare(str1, str2)

    Output:
    0

C# Example to analyze two strings utilizing String.Compare() strategy:

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //string variables
            string str1 = "JustTechReview";
            string str2 = "JustTechReview";

            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 = "JUSTTECHREVIEW";
            str2 = "JustTechReview";

            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
JustTechReview and JustTechReview are same
JUSTTECHREVIEW and JustTechReview are not same

Leave a Comment

error: Alert: Content is protected!!