C# String Comparison
In C#, strings can be compared using various methods and operators, such as the ==
operator, the Equals()
method, and the Compare()
method. These methods allow you to check for equality or determine the relative order of strings.
Key Topics
1. Using the ==
Operator
Example: Equality Operator
string str1 = "Hello";
string str2 = "Hello";
Console.WriteLine(str1 == str2); // Outputs: True
2. Using the Equals()
Method
Example: Equals Method
string str1 = "Hello";
string str2 = "hello";
bool isEqual = str1.Equals(str2);
Console.WriteLine(isEqual); // Outputs: False
3. Using the Compare()
Method
The Compare()
method returns an integer indicating the relative order of the strings.
Example: Compare Method
string str1 = "Apple";
string str2 = "Banana";
int result = string.Compare(str1, str2);
Console.WriteLine(result); // Outputs: -1
A result of -1
indicates that str1
precedes str2
in sort order.
4. The StringComparison
Enum
You can specify comparison rules using the StringComparison
enumeration.
Example: Case-Insensitive Comparison
string str1 = "hello";
string str2 = "HELLO";
bool isEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isEqual); // Outputs: True
Key Takeaways
- Use
==
for simple equality checks. Equals()
provides more options for comparison.Compare()
helps determine sort order between strings.- The
StringComparison
enum allows for culture-specific and case-insensitive comparisons.