繁体   English   中英

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

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

我想用另一个单词替换长字符串中所有出现的单词,例如,如果我想在下面的字符串中更改所有出现的单词“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."

我想我会使用replaceAll()方法,但我只是插入诸如的单词

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

您需要进行两项更改:

  • 字符串在Java中是不可变的 - replaceAll方法不会修改字符串 - 它会创建一个新字符串。 您需要将回调结果分配回变量。
  • 使用单词边界( '\\b' ),否则every都会变得eextremely

所以你的代码看起来像这样:

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

您可能还想考虑“非常”或“非常”想要发生的事情。 例如,您可能希望它分别变为“极端”和“极端”。

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

消息= message.replaceAll( “\\\\ B” +字+ “\\\\ B”,newword);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM