Home » .Net

Comparing two strings in C#

Comparing two strings in C#: Here, we will learn how to compare two strings using string.CompareTo() method in C#.Net?

Given two strings and we have to check whether strings are same or not?

string.CompareTo() Method

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

Syntax:

int string.CompareTo(string str);

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

Return values:

  • 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 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.