This tutorial will teach us how to compare strings in c# with an example.
Comparing strings using C#
There are many types of string comparison methods which are discussed below.
Remember that the choice of comparison method depends on your specific requirements, such as case sensitivity, culture, and sorting rules.
using string.Equals()
The code snippet you provided demonstrates a case-insensitive ordinal comparison method in C#.
Main method:
-
-
- We declared a boolean variable
IsEqual
. - We used the
string.Equals
method to compare the two strings:"TEMPLATE"
and"template"
. StringComparison.OrdinalIgnoreCase
specifies that the comparison should be case-insensitive.- The result of the comparison is stored in
IsEqual
. - Finally, we print the value of
IsEqual
to the console.using System; namespace compare_string { internal static class Program { static void Main(string[] args) { var IsEqual = string.Equals("TEMPLATE", "template", StringComparison.OrdinalIgnoreCase); Console.WriteLine(IsEqual); Console.ReadLine(); } } }
Output:
- When you run this program, it will display True because the comparison between “TEMPLATE” and “template” ignores the case. In summary, this code snippet compares two strings while ignoring their case using the string. Equals method with the StringComparison.OrdinalIgnoreCase option. It’s a concise way to check if two strings are equal regardless of letter casing.
- We declared a boolean variable
-
using (==) operator
- The equality operators == and != can be used to compare strings.
- They perform a case-sensitive, ordinal comparison by default.Main method:
- You’ve declared two string variables:
name1
andname2
. name1
is assigned the value"Kuheli"
, andname2
is assigned the value"kuheli"
.- The line
bool areEqual = name1 == name2;
compares the values ofname1
andname2
. - The equality operator (
==
) checks if the strings are identical (i.e., have the same characters in the same order). - Since the comparison is case-sensitive, the result will be
false
because"Kuheli"
and"kuheli"
differ in capitalization.using System; namespace compare_str { class Program { static void Main(string[]args) { string name1 = "Kuheli"; string name2 = "kuheli"; bool Equal = name1 == name2; Console.WriteLine($"The names are equal? {Equal}"); Console.ReadKey(); } } }
Output:
The code compares the strings"Kuheli"
and"kuheli"
using the equality operator and prints whether they are equal or not. Since the comparison is case-sensitive, the output will be “The names are equal? False.”