Compare Two Strings In C#
Code snippet for how to Compare Two Strings In C# with sample and detail explanation
C# is one of the widely-used languages for applications development. One common operation while working with C# is comparing strings. This article throws light on how two strings can be compared in C#.
Code snippet for String Comparison in C#
Here is a basic program that demonstrates how to compare two strings in C#:
using System;
class Program
{
static void Main()
{
string str1 = "Hello World";
string str2 = "hello world";
int result = string.Compare(str1, str2);
Console.WriteLine("Result of comparison: " + result);
}
}
Code Explanation for String Comparison in C#
Let’s go through the code step by step.
First, the System
namespace is used which contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
The Program
class is the next component, which is the central container of the program.
Inside the main program class, we defined a Main
method. The Main
method is the entry point of a C# console application or any application in C#. When the application is started, the Main
method is the first method that is invoked.
In the Main
method, two string variables str1
and str2
are defined with the values “Hello World” and “hello world” respectively.
Next, string.Compare(str1, str2)
method is used to compare str1
and str2
. This method returns an integer that indicates their relative position in the sort order.
Here are the possible return values:
- Less than zero: str1 is less than str2.
- Zero: str1 equals str2.
- Greater than zero: str1 is greater than str2.
The result of the comparison is printed out using Console.WriteLine()
. If the printed result is 0, it means that str1
and str2
are equal. If the result is less than 0, it means str1
is less than str2
. Conversely, if the result is more than 0, it indicates str1
is greater than str2
.
In this particular example, as the strings are equal but differ in case, the output will be a positive integer. This indicates that str1
is greater than str2
considering the case sensitivity.
Remember that string comparison in C# is case-sensitive. To ignore case during comparison, you can use string.Compare(str1, str2, true)
where true
indicates that the comparison should ignore case.