aspose file tools*
The moose likes Beginning Java and the fly likes Removing a word from a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Removing a word from a String" Watch "Removing a word from a String" New topic
Author

Removing a word from a String

Ben Wong
Greenhorn

Joined: Mar 27, 2006
Posts: 19
Hi

I am trying to remove a word from a String.
I was using the replaceAll("theword", "") method but it can sometimes affect the other words in the String. e.g. if im trying to remove "oil" the words containing that will be affected such as "foil" or "boil".

Any solutions would be greatly appreciated.

Thanks
Ben Wong
Greenhorn

Joined: Mar 27, 2006
Posts: 19
Here is the solution i have, but i want to know if theres anything in the String Class that can do this:

private String removeWord(String unwanted, String sentence)
{
StringTokenizer st = new StringTokenizer(sentence);
String remainder = "";

while(st.hasMoreTokens())
{
String temp = st.nextToken();

if(!temp.equals(unwanted))
{
remainder += temp+" ";
}
}

return remainder.trim();
}
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
Originally posted by Ben Wong:
Hi

I am trying to remove a word from a String.
I was using the replaceAll("theword", "") method but it can sometimes affect the other words in the String. e.g. if im trying to remove "oil" the words containing that will be affected such as "foil" or "boil".

Any solutions would be greatly appreciated.

Thanks

Use the regular expression \b to inticate you only want match words at a word boundary.

replaceAll("\\btheword\\b", "");


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Ben Wong
Greenhorn

Joined: Mar 27, 2006
Posts: 19
thank you!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Removing a word from a String