String CompareTo Example to compare strings
In this post we will see how to use String.CompareTo Method to match two strings. CompareTo Method returns following values:
- CompareTo Method returns.
- Less than Zero.{when value of string with which we are compairing is greater than second value}.
- Zero when strings match.
- Greater than Zero {when value of second string is greater than value with which we are compairing}.
Step 1: Take two Textboxes to receive input, one label to show output message and Button.
Step 2: Codebehind:
protected void btnCompare_Click(object sender, EventArgs e)
{
int a = txtInputValue1.Text.ToString().CompareTo(txtInputValue2.Text);
lblResult.Text = a.ToString();
if (a == 0)
{
lblResult.Text = "Strings entered are same.";
}
else
{
lblResult.Text = "Strings entered are not same.";
}
}
Final Output: