tags:

views:

10006

answers:

6

Say I have 2 strings,

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

I want to preform 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, does anyone know of another (possibly better) way to accomplish this without caring about case-sensitivity?

A: 

It will look for the exact sequence of characters that are passed to it.

If you want to ignore case then what you have there looks fine to me.

Arthur Thomas
+1  A: 

DrJava would be an extremely easy way to test this when the documentation fails you. Just type a couple of test cases into its Interactions window, and you should find out.

Denis Bueno
Thanks, I'll have to check it out - I'd never heard of it before now.
Kamikaze Mercenary
+8  A: 

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(s2), Pattern.CASE_INSENSITIVE).matcher(s1).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.

Dave L.
Great, I thought so but wasn't 100% on it. Thanks! :)
Kamikaze Mercenary
A: 

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

SCdF
+5  A: 

One problem with the answer by Dave L. is when s2 contains regex markup such as \d etc.

You want to call Pattern.quote() on s2:

Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find();
Matt Quail
Nice catch Matt. I'm curious to know what method is more efficient - the lowercase contains, or your pattern solution. Isn't using a pattern less efficient for a single comparison, but more efficient for multiple comparisons?
Kamikaze Mercenary
The .toLowerCase().contains() method will probably be faster in most cases. I would probably prefer that style for lower complexity, too.
Matt Quail
A: 

Yes this is achievable, I just did it for a school assignment actually.

// Start Code

String s1 = "abBaCca"; String s2 = "bac";

String s1Lower = s1;

//s1Lower is exact same string, now convert it to lowercase, I left the s1 intact for print purposes if needed

s1Lower = s1Lower.toLowerCase();

if (s1Lower.contains(s2)) {

//THIS statement will be TRUE
String trueStatement = "TRUE!"

}

return trueStatement;

// End Code

This code will return the String "TRUE!" as it found that your characters were contained.

Bilbo Baggins