Home » C#.Net

String.Compare() method with example in C#

C# String.Compare() method: Here, we are going to learn about the Compare() method of String class with example.
Submitted by IncludeHelp, on March 17, 2019

C# String.Compare() Method

String.Compare() method is used to compare two string objects, it returns values 0, less than 0 or greater than 0 based on the difference of first dissimilar characters.

Syntax:

    int String.Compare(String1, String2);

Parameter: It accepts two strings to compare.

Return value: It returns an int value – which may 0, less than 0 or greater than 0.

Example:

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

    Output:
    0

C# Example to compare two strings using String.Compare() method

using System;
using System.Text;

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

            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 = "INCLUDEHELP";
            str2 = "IncludeHelp";

            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
IncludeHelp and IncludeHelp are same
INCLUDEHELP and IncludeHelp are not same

Reference: String.Compare Method

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.