Compare strings or characters for equality in C# (ignoring case)

What happened

When solving problems on platforms like Codeforces or LeetCode, it’s common to encounter situations where you need to compare characters or strings for equality while ignoring case. Here are some commonly used approaches that I’ve documented.

Solution

String Section

Method 1 – string.Compare

string.Compare(strA, strB , StringComparison.OrdinalIgnoreCase);

To achieve a case-insensitive comparison, you can use StringComparison.OrdinalIgnoreCase along with string.Compare.

When using this approach, the return values have the following meanings:

  • 0: The strings are considered equal when compared ignoring case.
  • Less than 0: strA is considered lexicographically less than strB.
  • Greater than 0: strA is considered lexicographically greater than strB.

For an actual problem example, refer to Codeforces 1703A YES or YES? Solution & Explanation.

Method 2 – Convert to the Same Case Before Comparison

Another approach is to convert both strings to the same case (either uppercase or lowercase) and then perform the comparison.

bool res1 = strA.ToUpper() == strB.ToUpper();
bool res2 = strA.ToLower() == strB.ToLower();

Character Section

⚠️Method 1 – Using ASCII Codes

bool res = Math.Abs(charA-charB) == 32 || (charA==charB);

This method leverages the ASCII code property where the difference between lowercase ‘a’ and uppercase ‘A’ is 32. However, it’s important to note that this approach is only suitable when comparing characters within the range of English letters.

If the comparison is not constrained to English letters, unexpected results may occur.

For example, the decimal ASCII value of uppercase ‘A’ is 65. Without proper constraints, characters like ‘!’ (ASCII decimal 33) could be incorrectly deemed equivalent.

Method 2 – Convert to the Same Case Before Comparison

bool res1 = char.ToUpper(charA) == char.ToUpper(charB);
bool res2 = char.ToLower(charA) == char.ToLower(charB);
Klook.com

Conclusion

Reference

💔 The entire article was written and tested independently. Feel free to quote or reference, but please avoid copying the entire content verbatim.

🧡You can support our team by sharing the post or clicking some ads, Thanks a lot

If you have any problem about this post, please feel free to ask~

🍽️We’re also actively seeking collaboration opportunities, whether it’s through friendly links on partner sites or advertising partnerships

Some Random notes

Leave a Reply

Your email address will not be published. Required fields are marked *