jQuery in Action, 3rd edition
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 - lets.talk.about.help
Dont wait for forum answers
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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: 46337
"Ubuntu Climber," please check the JavaRanch naming policy and adjust your displayed name accordingly.
I agree. Here's the link: http://aspose.com/file-tools
subject: Strings contained in strings
It's not a secret anymore!