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 ");
You need to make two changes:
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.'\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.
story = story.replaceAll("very ", "extremely ");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With