如何用java中的另一个单词替换字符串中出现的所有单词?

如何用java中的另一个单词替换字符串中出现的所有单词?,java,string,replace,Java,String,Replace,我想用另一个单词替换长字符串中出现的所有单词,例如,如果我想将下面字符串中出现的所有单词“very”都改为“extrement” 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." 我想我会使用replaceAll()

我想用另一个单词替换长字符串中出现的所有单词,例如,如果我想将下面字符串中出现的所有单词“very”都改为“extrement”

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."
我想我会使用
replaceAll()
方法,但我会简单地插入如下单词吗

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

您需要进行两项更改:

  • 字符串在Java中是不可变的,
    replaceAll
    方法不会修改字符串,而是创建一个新的字符串。您需要将回调的结果分配给变量
  • 使用单词边界(
    '\b'
    ),否则
    每一个
    都将变成
    每一个
因此,您的代码如下所示:

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

你也可能想考虑你想要发生什么“非常”或“非常”。例如,您可能希望它分别变成“极端”和“极端”

message=message.replaceAll(“\\b”+word+“\\b”,newword)

如果这是Java,那么
string
应该大写。
story = story.replaceAll("\\bvery\\b", "extremely");