×

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# - Compare Two Strings Using string.CompareTo() Method

Given two strings and we have to check whether strings are same or not?
[Last updated : March 20, 2023]

string.CompareTo() Method

The string.CompareTo() is a method of string class, it is used to compare two strings.

Syntax

int string.CompareTo(string str);

Return values

Method returns 0, greater than 0 or less than 0.

  • 0 - If strings matched.
  • >0 - First string is greatest on the basis of Unicode character.
  • <<0 - First string is smallest on the basis of Unicode character.

C# program to compare two strings using string.CompareTo() method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      string str = "Hello";

      if (str.CompareTo("Hello") == 0) {
        Console.WriteLine("String is matched");
      } else {
        Console.WriteLine("String is not matched");
      }

      if (str.CompareTo("Hiii") == 0) {
        Console.WriteLine("String is matched");
      } else {
        Console.WriteLine("String is not matched");
      }
    }
  }
}

Output

String is matched
String is not matched

C# Basic Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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