0

I want to know if a word is the same as a other, but large and lower case shouldn't matter. some how like this:

String a = new String "test";
String b = new String "Test";
a.equals(b); // should be true;
FunkyFelix
  • 19
  • 3

2 Answers2

10

You can use String::equalsIgnoreCase

boolean check = a.equalsIgnoreCase(b);

Note : the declaration of your Strings is not correct it should be :

String a = "test";// or String a = new String("test");
String b = "Test";// or String b = new String("Test");
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

An alternative is to change both to lowerCase or upperCase and then compare:

String a = "test";
String b = "Test";
System.out.println(a.toLowerCase().equals(b.toLowerCase())); // prints true
achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • This solution seems to be worse. First, equalsIgnoreCase is likely more optimized. Second, using equalsIgnoreCase is much clearer. – Amongalen Jun 14 '18 at 15:08
  • 2
    @Amongalen It likely is worse; hence why I started the post with "*An alternative is...*". – achAmháin Jun 14 '18 at 15:10
  • It might be worth noting that these options are not equivalent, as the case-transformations in unicode are not bijective - there are several upper-case letters that map to the same lower-case letter, and also several lower-case letters that map to the same upper-case. Some lower-case letters even map to multiple upper case letters (like German `ß` => `SS`). In addition, `String.equalsIgnoreCase` does not use locale specific casing rules, while `String.toLowerCase` and `toUpperCase` do. Short version - it's more complicated that most people think, and each version can yield surprising results. – Hulk Jun 15 '18 at 06:43
  • See also https://stackoverflow.com/questions/4446643/java-string-equalsignorecase-vs-switching-everything-to-upper-lower-case and https://stackoverflow.com/questions/15518731/understanding-logic-in-caseinsensitivecomparator – Hulk Jun 15 '18 at 06:48