Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ");
like image 387
user386537 Avatar asked Dec 03 '22 05:12

user386537


2 Answers

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.

like image 123
Mark Byers Avatar answered Dec 15 '22 21:12

Mark Byers


story = story.replaceAll("very ", "extremely ");
like image 24
Sjoerd Avatar answered Dec 15 '22 22:12

Sjoerd