use*_*537 4 java string replace
我想用另一个单词替换长字符串中所有出现的单词,例如,如果我想在下面的字符串中更改所有出现的单词"very"和"extreme".
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."
Run Code Online (Sandbox Code Playgroud)
我想我会使用这个replaceAll()方法但是我只是插入诸如的单词
story.replaceAll("very ", "extremely ");
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 15
您需要进行两项更改:
replaceAll方法不会修改字符串 - 它会创建一个新字符串.您需要将回调结果分配回变量.'\b')否则every将成为eextremely.所以你的代码看起来像这样:
story = story.replaceAll("\\bvery\\b", "extremely");
Run Code Online (Sandbox Code Playgroud)
您可能还想考虑"非常"或"非常"想要发生的事情.例如,您可能希望它分别变为"极端"和"极端".