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.
A possible alternative might be abusing Regex. This is quite performance-intensive with dynamically changing strings, but if you are comparing against constants it could be an alternative:
Matcher matcher = Pattern.compile("^" + myOtherString + "$",
Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.UNICODE_CASE).matcher();
if (matcher.matches(myString)) {
// ...
}
This anchors the string you want to compare against, specifies Unicode-aware case-insensitive matching of the Literal string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.