[英]What is the correct alternative to Java's equalsIgnoreCase?
關於為什么以及何時java.lang.String.equalsIgnoreCase
因錯誤使用語言環境而失敗的例子有很多很多。
但我沒有找到任何正確方法的例子。 與java.lang.String.toUpperCase
不同,沒有帶語言環境參數的版本。 將兩個字符串轉換為大寫或小寫似乎都是浪費。 特別是當您正在進行大量比較的應用程序時。
在考慮區域設置和性能的情況下,進行忽略大小寫字符串比較的正確方法是什么?
根據此頁面 ,您可以使用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);
(從以上網站復制......)
顯然,在其他情況下,您可能會以不同的方式選擇區域設置。
對於@fge - 這個Oracle Bug Report給出了一個發生的事情的例子。
可能的替代方案可能是濫用正則表達式。 這是動態更改字符串的性能密集型,但如果您要與常量進行比較,則可能是另一種選擇:
Matcher matcher = Pattern.compile("^" + myOtherString + "$",
Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.UNICODE_CASE).matcher();
if (matcher.matches(myString)) {
// ...
}
這將錨定您要比較的字符串,指定Literal字符串的Unicode感知不區分大小寫的匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.