C# String.Compare() Method with Example

In this tutorial, we will learn about the String.Compare() method with its usage, syntax, and examples. By IncludeHelp Last updated : April 07, 2023

C# String.Compare() Method

The 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(s)

  • String1: The first string to be compared.
  • String2: The second string to be compared.

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




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.