如何使我的字符串比较不区分大小写? [英] How do I make my string comparison case-insensitive?
问题描述
我创建了一个Java程序来比较两个字符串:
I created a Java program to compare two strings:
String str = "Hello";
if (str.equals("hello")) {
System.out.println("match");
} else {
System.out.println("no match");
}
区分大小写.我该如何更改以免更改?
It's case-sensitive. How can I change it so that it's not?
推荐答案
The best way is to use str.equalsIgnoreCase("foo")
. It's optimized specifically for this purpose.
在将它们与 equals
进行比较之前,您还可以将两个字符串都转换为大写或小写形式.对于其他可能没有等价于 equalsIgnoreCase
的语言,这是一个非常有用的技巧.
You can also convert both strings to upper- or lowercase before comparing them with equals
. This is a trick that's useful to remember for other languages which might not have an equivalent of equalsIgnoreCase
.
str.toUpperCase().equals(str2.toUpperCase())
如果您使用的是非罗马字母,请注意 equalsIgnoreCase
的JavaDoc这部分内容,
If you are using a non-Roman alphabet, take note of this part of the JavaDoc of equalsIgnoreCase
which says
请注意,此方法不考虑语言环境,并且会导致某些地区的搜索结果不令人满意.整理器一个>类提供了对语言环境敏感的比较.
Note that this method does not take locale into account, and will result in unsatisfactory results for certain locales. The Collator class provides locale-sensitive comparison.
这篇关于如何使我的字符串比较不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!