How to use the Compare method of the string class in C#?


The Compare method compares two specified string objects and returns an integer that indicates their relative position in the sort order.

Firstly, set the strings.

string str1 = "Jack";
string str2 = "Mac";

Now compare the strings using the Compare() method and if the comparison results 0, then it would mean the strings are equal.

String.Compare(str1, str2) == 0

Let us see the complete example.

Example

 Live Demo

using System;
namespace StringApplication {
   class StringProg {
      static void Main(string[] args) {
         string str1 = "Jack";
         string str2 = "Mac";
         if (String.Compare(str1, str2) == 0) {
            Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
         } else {
            Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
         }
         Console.ReadKey() ;
      }
   }
}

Output

Jack and Mac are not equal strings.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements