File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Strings contained in strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strings contained in strings" Watch "Strings contained in strings" New topic

Strings contained in strings

John Lockheart
Ranch Hand

Joined: Oct 13, 2006
Posts: 115
What's the best way to go about checking if a String being searched for is contained within another String (ignoring case).

ex) Cat is contained in Catastraphy

I searched the string class online but found no functions that might help me do this. Maybe just using indexOf() with a string parameter, because that way if I don't get back an index it's not there, and if I do it is there? I'm trying to keep a record of which strings contain other strings, like all the strings in a list that contain the word "Cat" for example. Thanks
Jorge Pinho

Joined: May 16, 2003
Posts: 25

Hi John,

You have to use regular expressions...

look for...



Pattern Class, to understand Regular Expressions

Jorge Pinho / SCJP 5
Live Help via Skype -
Dont wait for forum answers
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

Using indexOf() this way is common and a fine thing to do; but it will only find exact matches, including letter case. A more general solution would be to use regular expressions -- String.matches() or its more general form java.util.regex.Pattern.matches(). Something like

// Keep "p", use for all your Strings to check if they contain "cat"
Pattern p = Pattern.compile(".*cat.*", Pattern.CASE_INSENSITIVE);

// For each string you want to match
Matcher m = p.matcher(theString);
boolean containsCatIgnoringCase = m.matches();

[Jess in Action][AskingGoodQuestions]
Sean Connery

Joined: Feb 20, 2008
Posts: 5
You could also try doing:

Then test the value of i to see if "cat" existed in the original string.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45266
"Ubuntu Climber," please check the JavaRanch naming policy and adjust your displayed name accordingly.
I agree. Here's the link:
subject: Strings contained in strings
It's not a secret anymore!