EqualsIgnoreCase() 未按预期工作。
EqualsIgnoreCase() not working as intended.
当我运行下面的程序时它只打印
equals says they are equal
但是从 java8 中的 equalsIgnoreCase 文档我们有:
Two characters c1 and c2 are considered the same ignoring case if at
least one of the following is true:
• Applying the method
java.lang.Character.toUpperCase(char) to each character produces the same result
public class Test {
public static void main(String[] args) {
String string1 = "abc\u00DF";
String string2 = string1.toUpperCase();
if (string1.equalsIgnoreCase(string2))
System.out.println("equalsIgnoreCase says they are equal");
if (string1.toUpperCase().equals(string2.toUpperCase()))
System.out.println("equals says they are equal");
}
}
所以我的问题是为什么这个程序不打印
equalsIgnoreCase says they are equal
因为在两个操作中都使用大写字符。
你是using/comparing德语ß符号,它的大写字母产生SS...所以你需要使用 Locale.German
if (string1.toUpperCase(Locale.GERMAN).equals(string2.toUpperCase(Locale.GERMAN)))
那将 return 正确....
是的,没错。
if (string1.equalsIgnoreCase(string2)) ....
忽略string1和string2的大小写
if (string1.equals(string2)) ....
将检测到有不同的字母并且不打印..它们是相等的。
您的第二个大写转换示例也可以。
当我运行下面的程序时它只打印
equals says they are equal
但是从 java8 中的 equalsIgnoreCase 文档我们有:
Two characters c1 and c2 are considered the same ignoring case if at least one of the following is true:
• Applying the method java.lang.Character.toUpperCase(char) to each character produces the same result
public class Test {
public static void main(String[] args) {
String string1 = "abc\u00DF";
String string2 = string1.toUpperCase();
if (string1.equalsIgnoreCase(string2))
System.out.println("equalsIgnoreCase says they are equal");
if (string1.toUpperCase().equals(string2.toUpperCase()))
System.out.println("equals says they are equal");
}
}
所以我的问题是为什么这个程序不打印
equalsIgnoreCase says they are equal
因为在两个操作中都使用大写字符。
你是using/comparing德语ß符号,它的大写字母产生SS...所以你需要使用 Locale.German
if (string1.toUpperCase(Locale.GERMAN).equals(string2.toUpperCase(Locale.GERMAN)))
那将 return 正确....
是的,没错。
if (string1.equalsIgnoreCase(string2)) ....
忽略string1和string2的大小写
if (string1.equals(string2)) ....
将检测到有不同的字母并且不打印..它们是相等的。 您的第二个大写转换示例也可以。