Compare Strings or Characters for Equality in Java (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 – equalsIgnoreCase()

boolean res = strA.compareToIgnoreCase(strB);

The equalsIgnoreCase method returns a boolean value where true indicates equality and false indicates inequality.

Method 2 – compareToIgnoreCase()

int res = strA.compareToIgnoreCase(strB);

The return value is an int, representing different meanings:

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

This feature has been available since Java 2, so it is a fundamental syntax and compatibility issues need not be a concern.

Here can see the example : Codeforces 112A Petya and Strings Solution & Explanation

Method 3 – Convert to the Same Case Before Comparison

boolean res1 = strA.toUpperCase().equals(strB.toUpperCase());
boolean res2 = strA.toUpperCase().equals(strB.toLowerCase());

Character Section

⚠️Method 1 – Using ASCII Codes

boolean res = Math.abs(charA - charB) == 32 || charA == charB;

This method leverages the ASCII characteristics where uppercase and lowercase English letters have a decimal difference of 32.

  • Math.abs(charA – charB) == 32: Indicates one character is uppercase and the other is lowercase.
  • charA == charB: Indicates the characters are the same case (either both uppercase or both lowercase).

⚠️ It’s important to ensure that the input characters fall within the range of ‘a’ to ‘Z’ to avoid unexpected behavior.

For instance, the ASCII decimal value of uppercase ‘A’ is 65, while the exclamation mark (!) has an ASCII decimal value of 33. Although they also have a difference of 32, they are definitely not equal!

Method 2 – Convert to the Same Case Before Comparison

boolean res = Character.toLowerCase(charA) == Character.toLowerCase(charB);

Simple and Practical.

Of course, you can convert a Character to a String and then apply the method mentioned above, but that might feel a bit indirect.

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 *