In this example, i’ll show you How to compare two strings by ignoring case in C# Windows Form Application.
we can compare two specified string objects using String.Compare method. String.Compare() method returns an integer that indicates their relative position in the sort order. this method is overloaded.
String.Compare(String, String, Boolean) method overload compare two specified string objects by ignoring or honoring their case. so we can use this overloaded method to compare two string objects by ignoring case (case insensitive string comparison).
this overloaded method require three parameters. First two parameters are two string objects those we need to compare. and third parameter is a Boolean value. we must set the Boolean parameter to True when we need to ignore case during comparison. or we must set the Boolean parameter to False to honor case during string comparison.
if the method returned integer is less than zero, then the first string (strA) is less than the second string (strB). if it return zero, then two specified strings are equals. and if the return value is greater than zero, then the first string is greater than the second string.
the following c# example code demonstrate us how can we compare two strings by ignoring their case.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
private void button1_Click(object sender, EventArgs e) { string testString1 = textBox1.Text; string testString2 = textBox2.Text; int result = string.Compare(testString1, testString2, true); label1.Text = ""; if (result == 0) { label1.Text += "Two strings are equal"; } else if (result == 1) { label1.Text += "Test String1 is greater than Test String2"; } else if (result == -1) { label1.Text += "Test String1 is less than Test String2"; } } |
Output: