Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Removing a word from a String

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic