Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Finding a word within a string

807569May 22 2006 — edited May 22 2006
Hey everyone,

Just having a little trouble with something.

I'm trying to find a word -- that is, not a substring, an actual word as defined by the english language -- within a string.

For example I don't want "hell" to be found in "hello".. only "hello" to be found.

Currently i've got two strings, one is the sentance (String input), and one is the word to be found in the sentance (String word). I need the program to find the WORD, and then go back and search for the word again and again and again until it reaches the end of the string.

This is what I've got thus far:
		for(i = 0; i < input.length(); i++)
		{
			// This statement checks the string "input" for the string "word" starting at offset 0 (as this is what the variable was first defined as)
			if(input.indexOf(word, offset) >= 0) 
			{
				// If it finds the word at all, this line increases the offset ahead of this word so it doesn't simply find the same word again
				offset = offset + (input.indexOf(word)) + (word.length());
				times++;
			}
		}
At the moment this searches for the sub-string, not the WORD which is what I would like it to do.

What's the easiest way of going about this? I've been fiddling around trying to add extra sections to the if statement, for example
if((input.indexOf(word, offset) >= 0) && (input.charAt(offset +1) == 32))
(32 as in the ASCII character for a space, which would do what I wanted it to do)

But I eventually get errors because at some stage or another the charAt is going to be higher than the actual length of the String. Plus, this only looks if there's a space next to the word - a word can be valid if it has a ! next to it for example, or a comma...

Thanks for any help :)

viddy
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 19 2006
Added on May 22 2006
1 comment
226 views