[英]What is the correct alternative to Java's equalsIgnoreCase?
There are lots and lots of examples on why and when java.lang.String.equalsIgnoreCase
will fail because of incorrect use of the locale. 关于为什么以及何时
java.lang.String.equalsIgnoreCase
因错误使用语言环境而失败的例子有很多很多。
But I did not find any examples of the correct way. 但我没有找到任何正确方法的例子。 Unlike
java.lang.String.toUpperCase
there is no version with a locale parameter. 与
java.lang.String.toUpperCase
不同,没有带语言环境参数的版本。 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: 根据此页面 ,您可以使用Collator执行不区分大小写的相等性,如下所示:
//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. 对于@fge - 这个Oracle Bug Report给出了一个发生的事情的例子。
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. 这将锚定您要比较的字符串,指定Literal字符串的Unicode感知不区分大小写的匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.