How to Initialize and Compare Strings in C#?

CsharpProgrammingServer Side Programming

To initializes a string in C# is an easy task. Let’s say you want to set a name “Amit”, for that, initialize your string as.

String str1 = "Hello, World!";

To compare strings, use the the following C# method.

public static int Compare(string str1, string str2)

To compare, if −

String.Compare(str1, str2) == 0

If the above is equal to 0, then both the strings are equal.

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

The following is an example that shows the comparison of one string to another.

Example

 Live Demo

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         string str1 = "John";
         string str2 = "Andy";
         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

John and Andy are not equal strings.
raja
Published on 18-Sep-2018 08:32:33
Advertisements