user386537
user386537

Reputation: 461

how to replace all occurences of a word in a string with another word in java?

I want to replace all occurrences of a word in a long string with another word, for example if I am wanting to change all occurrences of the word "very" with "extremely" in the following string.

string story = "He became a well decorated soldier in the line of fire when he and his men walked into the battle. He acted very bravely and he was very courageous."

I guess I would use the replaceAll() method but would I simply insert the words such as

story.replaceAll("very ", "extremely ");

Upvotes: 4

Views: 20399

Answers (3)

Creative_Cimmons
Creative_Cimmons

Reputation: 265

message=message.replaceAll("\\b"+word+"\\b",newword);

Upvotes: -1

Mark Byers
Mark Byers

Reputation: 838076

You need to make two changes:

  • Strings are immutable in Java - the replaceAll method doesn't modify the string - it creates a new one. You need to assign the result of the call back to your variable.
  • Use word boundaries ('\b') otherwise every will become eextremely.

So your code would look like this:

story = story.replaceAll("\\bvery\\b", "extremely");

You may also want to consider what you want to happen to "Very" or "VERY". For example, you might want this to become "Extremely" and "EXTREMELY" respectively.

Upvotes: 17

Sjoerd
Sjoerd

Reputation: 75588

story = story.replaceAll("very ", "extremely ");

Upvotes: 2

Related Questions