我有两个字符串,str1和str2。我如何检查str2是否包含在str1中,忽略大小写?


当前回答

你可以使用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时,您只需要修改一行代码。

其他回答

str1.toUpperCase().contains(str2.toUpperCase())

UPD:

原来的答案是使用toLowerCase()方法。但是,正如一些人正确地注意到的那样,Unicode中有一些例外,最好使用toUpperCase()。因为:

有些语言对于一个大写变体知道不止一个小写变体。

你可以使用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时,您只需要修改一行代码。

那么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.*");

我将使用包含方法和toUpper方法的组合,它们是String类的一部分。下面是一个例子:

String 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=真 搜索 2=假

如果你能够使用org.apache.commons.lang.StringUtils,我建议使用以下方法:

String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);