• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Removing a word from a String

 
Ben Wong
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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", "");
 
Ben Wong
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic