我有两个字符串,str1
和 str2
。如何检查是否忽略大小写地包含str2
在str1
中?
str1.toUpperCase().contains(str2.toUpperCase())
更新:
原回答使用了 toLowerCase()
方法。但是正如一些人正确指出的那样,Unicode 中存在一些异常情况,最好使用 toUpperCase()
。因为:
有些语言存在一个大写变体对应多个小写变体的情况。
int pos = str1.indexOf(str2)
或者不区分大小写 int pos = str1.toLowerCase().indexOf(str2.toLowerCase())
。 - Igor Artamonovtrue
。 - MartyIX那么matches()
呢?
String string = "Madam, I am Adam";
// Starts with
boolean b = string.startsWith("Mad"); // true
// Ends with
b = string.endsWith("dam"); // true
// Anywhere
b = string.indexOf("I am") >= 0; // true
// To ignore case, regular expressions must be used
// Starts with
b = string.matches("(?i)mad.*");
// Ends with
b = string.matches("(?i).*adam");
// Anywhere
b = string.matches("(?i).*i am.*");
String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);
toLowerCase()
方法:public boolean contains( String haystack, String needle ) {
haystack = haystack == null ? "" : haystack;
needle = needle == null ? "" : needle;
// Works, but is not the best.
//return haystack.toLowerCase().indexOf( needle.toLowerCase() ) > -1
return haystack.toLowerCase().contains( needle.toLowerCase() )
}
然后使用以下方式调用:
if( contains( str1, str2 ) ) {
System.out.println( "Found " + str2 + " within " + str1 + "." );
}
请注意,通过创建自己的方法,您可以重复使用它。因此,当有人指出您应该使用contains
而不是indexOf
时,您只需要更改一行代码。
我也赞同使用正则表达式的解决方案。代码将更加简洁。在我知道字符串将会很大的情况下,我不愿使用 toLowerCase(),因为字符串是不可变的,需要进行复制。另外,matches() 的解决方案可能会让人感到困惑,因为它将正则表达式作为参数(搜索 "Need$le" 可能会有问题)。
结合以上几个示例:
public boolean containsIgnoreCase( String haystack, String needle ) {
if(needle.equals(""))
return true;
if(haystack == null || needle == null || haystack .equals(""))
return false;
Pattern p = Pattern.compile(needle,Pattern.CASE_INSENSITIVE+Pattern.LITERAL);
Matcher m = p.matcher(haystack);
return m.find();
}
example call:
String needle = "Need$le";
String haystack = "This is a haystack that might have a need$le in it.";
if( containsIgnoreCase( haystack, needle) ) {
System.out.println( "Found " + needle + " within " + haystack + "." );
}
(注:您可能想根据您的需求以不同方式处理 NULL 和空字符串。我认为我所做的方式更接近 Java 字符串规范。)Pattern.CASE_INSENSITIVE|Pattern.LITERAL
- mike jonesString string1 = "AAABBBCCC";
String string2 = "DDDEEEFFF";
String searchForThis = "AABB";
System.out.println("Search1="+string1.toUpperCase().contains(searchForThis.toUpperCase()));
System.out.println("Search2="+string2.toUpperCase().contains(searchForThis.toUpperCase()));
搜索1=true
搜索2=false
"ß".toUpperCase().equals("SS")
。 - Simon