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

CsharpProgrammingServer Side Programming

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.
raja
Published on 18-Sep-2018 13:31:08
Advertisements