Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (5.3k points)

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?

1 Answer

0 votes
by (119k points)

Yes, contains is case sensitive. Here is another way for case insensitive matching using java.util.regex.Pattern with the CASE_INSENSITIVE flag:

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();

You need to use Pattern.quote() on s2 if regex special characters.

If you want to learn Java, then sign up in this Java Certification Program by Intellipaat. 

Related questions

0 votes
1 answer
0 votes
2 answers
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...