Home Exercises How to compare two strings in C#

How to compare two strings in C#

In this example we will create a program that compares 2 strings

To do this we will use the string.CompareTo() Method

This compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position

The following integers are returned

  • 0 – The strings are a match.
  • >0 – The first string is greatest on the basis of the Unicode character.
  • <0 – The first string is smallest on the basis of the Unicode character.

Example

Create a new console project, in this case ConsoleApp1 and enter the following code

In this example we will look for a match then display some console output to the user depending on what we get.

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string myString = "maxcsharp";
            // compare myString to maxcsharp
            // then display outcome to user depending on the comparison
            if (myString.CompareTo("maxcsharp") == 0)
            {
                Console.WriteLine("String is a match");
            }
            else
            {
                Console.WriteLine("String is not a match");
            }

            // compare myString to maxpython
            // then display outcome to user depending on the comparison
            if (myString.CompareTo("maxpython") == 0)
            {
                Console.WriteLine("String is a match");
            }
            else
            {
                Console.WriteLine("String is not a match");
            }
        }
    }
}

When run you should see something like this – I put a breakpoint after the last Console.WriteLine and ran in debug

String is a match
String is not a match