How to check if a String contains another String i

2018-12-31 08:45发布

Say I have two strings,

String s1 = "AbBaCca";
String s2 = "bac";

I want to perform a check returning that s2 is contained within s1. I can do this with:

return s1.contains(s2);

I am pretty sure that contains() is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like:

return s1.toLowerCase().contains(s2.toLowerCase());

All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?

标签: java string
17条回答
素衣白纱
2楼-- · 2018-12-31 09:03

Another easy-to-use method for finding a string inside a string is STRING.INDEXOF ()

  String str = new String("Welcome");
  System.out.print("Found Index :" );
  System.out.println(str.indexOf( 'o' ));

Found Index :4

www.tutorialspoint.com/java/java_string_indexof.htm

查看更多
浪荡孟婆
3楼-- · 2018-12-31 09:06

Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();

EDIT: If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.

查看更多
深知你不懂我心
4楼-- · 2018-12-31 09:06

You could simply do something like this:

String s1 = "AbBaCca";
String s2 = "bac";
String toLower = s1.toLowerCase();
return toLower.contains(s2);
查看更多
荒废的爱情
5楼-- · 2018-12-31 09:11

You can use regular expressions, and it works:

boolean found = s1.matches("(?i).*" + s2+ ".*");
查看更多
爱死公子算了
6楼-- · 2018-12-31 09:12

I'm not sure what your main question is here, but yes, .contains is case sensitive.

查看更多
登录 后发表回答