java 如何替换字符串中的最后一个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7146293/
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 the last word in a string
提问by Bitmap
Does anyone knows how to replace the last word in a String.
有谁知道如何替换字符串中的最后一个单词。
Currently I am doing:
目前我正在做:
someStr = someStr.replace(someStr.substring(someStr.lastIndexOf(" ") + 1), "New Word");
The above code replaces every single occurance of the word in the string.
上面的代码替换字符串中出现的每个单词。
Thanks.
谢谢。
回答by aioobe
You could create a new string "from scratch" like this:
您可以像这样“从头开始”创建一个新字符串:
someStr = someStr.substring(0, someStr.lastIndexOf(" ")) + " New Word";
Another option (if you really want to use "replace" :) is to do
另一种选择(如果你真的想使用“替换”:) 是做
someStr = someStr.replaceAll(" \S*$", " New Word");
replaceAll
uses regular expressions and \S*$
means a space, followed by some non-space characters, followed by end of string. (That is, replace the characters after the last space.)
replaceAll
使用正则表达式并\S*$
表示一个空格,后跟一些非空格字符,后跟字符串结尾。(即,替换最后一个空格后的字符。)
回答by JB Nizet
You're not far from the solution. Just keep the original string until the last index of " "
, and append the new word to this substring. No need for replace
here.
你离解决方案不远了。只需保留原始字符串直到 的最后一个索引" "
,并将新单词附加到此子字符串。replace
这里不需要。
回答by Waldo Bronchart
What your code is doing is replacing the substring by "New word".
您的代码正在做的是用“新词”替换子字符串。
Instead you need to substring first, and then do a replace on that string.
相反,您需要先进行子字符串化,然后对该字符串进行替换。
Here's how I would do it
这是我将如何做到的
someStr = someStr.substring(0, someStr.lastIndexOf(" ") + 1) + "New word"
回答by SBerg413
try:
尝试:
someStr = someStr.substring( someStr.lastIndexOf(" ") ) + " " + new_word;
回答by AlexR
use this: someStr.substring(0, someStr.lastIndexOf(" ")) + "New Word"
.
使用这个:someStr。substring(0, someStr.lastIndexOf(" ")) + "New Word"
.
You can also use regular expression, e.g. someStr.repalaceFirst("\s+\S+$", " " + "New Word")
你也可以使用正则表达式,例如 someStr.repalaceFirst("\s+\S+$", " " + "New Word")
回答by Muhammad Gelbana
Try this regex (^.+)b(.+$)
试试这个正则表达式 (^.+)b(.+$)
Example (Replace the last bcharacter)
示例(替换最后一个b字符)
System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", ""));