java - 如何用java中的另一个单词替换字符串中所有出现的单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3223791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to replace all occurences of a word in a string with another word in java?
提问by user386537
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.
我想用另一个词替换一个长字符串中出现的所有单词,例如,如果我想将以下字符串中所有出现的“very”更改为“extremely”。
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
我想我会使用该replaceAll()方法,但我会简单地插入诸如
story.replaceAll("very ", "extremely ");
回答by Mark Byers
You need to make two changes:
您需要进行两项更改:
- Strings are immutable in Java - the
replaceAllmethod 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') otherwiseeverywill becomeeextremely.
- 字符串在 Java 中是不可变的——该
replaceAll方法不会修改字符串——它会创建一个新的字符串。您需要将回调的结果分配给您的变量。 - 使用词边界(
'\b') 否则every会变成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.
您可能还想考虑您希望“非常”或“非常”发生什么。例如,您可能希望将其分别变为“Extremely”和“EXTREMELY”。
回答by Sjoerd
story = story.replaceAll("very ", "extremely ");
回答by Creative_Cimmons
message=message.replaceAll("\\b"+word+"\\b",newword);
message=message.replaceAll("\\b"+word+"\\b",newword);

