×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

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


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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