There are lots and lots of examples on why and when java.lang.String.equalsIgnoreCase
will fail because of incorrect use of the locale.
But I did not find any examples of the correct way. Unlike java.lang.String.toUpperCase
there is no version with a locale parameter. Converting both strings to upper or lower case seem to be wasteful. Especially when you are working on a application doing a lot of comparisons.
What is the correct way to make a ignore case string comparison, taking both locale and performance into consideration?
According to this page, you can use Collator to do case insensitive equality as follows:
//retrieve the runtime user's locale
Locale locale = new Locale(getUserLocale());
//pass the user's locale as an argument
Collator myCollator = Collator.getInstance(locale);
//set collator to Ignore case but not accents
//(default is Collator.TERTIARY, which is
//case sensitive)
myCollator.setStrength(Collator.SECONDARY);
int i = myCollator.compare(stringA,stringB);
(Copied from the above site ...)
Obviously, in other contexts you might choose the locale differently.
For @fge - This Oracle Bug Report gives an example of the kind of thing that happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With