This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes finding phrases in a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "finding phrases in a String" Watch "finding phrases in a String" New topic
Author

finding phrases in a String

Theresa Marlin
Ranch Hand

Joined: Sep 23, 2009
Posts: 49
I have to do assignment:

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.

countCode("aaacodebbb") → 1
countCode("codexxcode") → 2
countCode("cozexxcope") → 2

I'm not sure exactly how to find/extract the word "code" out of a string. Do I use substring?

Thanks!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Substring is one way, but regular expressions would be easier for this. Check out java.util.regex.Pattern and java.util.regex.Matcher.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Really? I'd probably just use the indexOf methods and loop--easier than learning a mini-language, at least in my book :)
Theresa Marlin
Ranch Hand

Joined: Sep 23, 2009
Posts: 49
I'm pretty sure I have to use substring because I don't know any other methods.
Thanks for your help anyway!
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

You might be able to look up a method.

java.lang.String

And look at the indexOf methods.

(Not sure why that isn't linking to the docs.)
Theresa Marlin
Ranch Hand

Joined: Sep 23, 2009
Posts: 49
Thanks!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

David Newton wrote:Really? I'd probably just use the indexOf methods and loop--easier than learning a mini-language, at least in my book :)

I would have used indexOf as well, if one of the requirements wasn't the-third-character-can-be-anything.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Whoops, missed that part!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37936
    
  22
Now we have all worked out what the question was, where shall we look for the answer?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: finding phrases in a String
 
Similar Threads
Remove Chars from a String?
Difference bet "" and null
do while loop
Regular Expression Question
How many objects are eligible for garbage collection