String equality

In this chapter you will learn:

  1. String comparison for equality
  2. Equals method
  3. Compare and ignore case

String comparison for equality

We can use == to check the equality between two string values

using System;/*from   ja va2s  .  c  o  m*/

class Sample
{
    public static void Main()
    {
        string s1 = "java2s.com";
        string s2 = "java2s.coM";

        if (s1.ToUpper() == s2.ToUpper())
        {
            Console.WriteLine("equal");
        }

    }
}

The output:

Equals method

Equals method from string type provides the same functionality and adds more features.

using System;// j a va2  s. co  m

class Sample
{
    public static void Main()
    {
        string s1 = "java2s.com";
        string s2 = "java2s.coM";

        if (s1.ToUpper().Equals(s2.ToUpper()))
        {
            Console.WriteLine("equal");
        }

    }
}

The output:

Compare and ignore case

Further more we can compare two string ignoring the case by specifying case-insensitive option.

using System;//from j a  v a  2s .  co m

class Sample
{
    public static void Main()
    {
        string s1 = "java2s.com";
        string s2 = "java2s.coM";

        if (s1.Equals(s2, StringComparison.OrdinalIgnoreCase))
        {
            Console.WriteLine("equal");
        }
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Use the Concat() method to concatenate strings
  2. Use the addition operator (+) to concatenate strings
  3. Concat method with a String array
  4. Mix string and integer in string cancatenation
Home » C# Tutorial » String
string
String creation
Char in string
Compare strings
String equality
String concatanation
String copy
String Join
String split
String Search for Index
String contains
String start with
String insert
String case
Replacing substring
Remove from a string
Substring
Escape Characters
String verbatim
String padding
Switch on String
String trim
String intern
String normalization
Empty String