在 Java 中,如何检查字符串是否包含子字符串(忽略大小写)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2275004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:34:14  来源:igfitidea点击:

In Java, how do I check if a string contains a substring (ignoring case)?

javastringsubstring

提问by trinity

I have two Strings, str1and str2. How do I check if str2is contained within str1, ignoring case?

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

采纳答案by Igor Artamonov

str1.toLowerCase().contains(str2.toLowerCase())

回答by Vincent Ramdhanie

You can use the toLowerCase()method:

您可以使用以下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() )
}

Then call it using:

然后使用以下方法调用它:

if( contains( str1, str2 ) ) {
  System.out.println( "Found " + str2 + " within " + str1 + "." );
}

Notice that by creating your own method, you can reuse it. Then, when someone points out that you should use containsinstead of indexOf, you have only a single line of code to change.

请注意,通过创建自己的方法,您可以重用它。然后,当有人指出您应该使用contains代替 时indexOf,您只需更改一行代码。

回答by SOA Nerd

I'd use a combination of the contains method and the toUppermethod that are part of the String class. An example is below:

我将使用 contains 方法和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()));

This will return:

这将返回:

Search1=true
Search2=false


搜索 1 =真搜索 2=假

回答by Jim Raynor

How about matches()?

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

回答by Mojo

If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:

如果您能够使用org.apache.commons.lang.StringUtils,我建议使用以下内容:

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

回答by Michael Cooper

I also favor the RegEx solution. The code will be much cleaner. I would hesitate to use toLowerCase() in situations where I knew the strings were going to be large, since strings are immutable and would have to be copied. Also, the matches() solution might be confusing because it takes a regular expression as an argument (searching for "Need$le" cold be problematic).

我也喜欢 RegEx 解决方案。代码会干净很多。在我知道字符串会很大的情况下,我会犹豫是否使用 toLowerCase(),因为字符串是不可变的并且必须被复制。此外,matches() 解决方案可能会令人困惑,因为它需要一个正则表达式作为参数(搜索“Need$le”冷是有问题的)。

Building on some of the above examples:

基于上述一些示例:

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 + "." );
}

(Note: you might want to handle NULL and empty strings differently depending on your needs. I think they way I have it is closer to the Java spec for strings.)

(注意:您可能希望根据需要以不同方式处理 NULL 和空字符串。我认为他们的方式更接近于字符串的 Java 规范。)

Speed critical solutions could include iterating through the haystack character by character looking for the first character of the needle. When the first character is matched (case insenstively), begin iterating through the needle character by character, looking for the corresponding character in the haystack and returning "true" if all characters get matched. If a non-matched character is encountered, resume iteration through the haystack at the next character, returning "false" if a position > haystack.length() - needle.length() is reached.

速度关键的解决方案可能包括一个字符一个字符地遍历大海捞针,寻找针的第一个字符。当第一个字符匹配时(大小写不敏感),开始逐个字符地遍历针,在大海捞针中寻找相应的字符,如果所有字符都匹配,则返回“true”。如果遇到不匹配的字符,则在下一个字符处继续遍历 haystack,如果到达位置 > haystack.length() -needle.length(),则返回“false”。