How to replace the last word in a string
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.
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.)
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.
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"
try:
someStr = someStr.substring( someStr.lastIndexOf(" ") ) + " " + new_word;
use this: someStr.substring(0, someStr.lastIndexOf(" ")) + "New Word"
.
You can also use regular expression, e.g. someStr.repalaceFirst("\s+\S+$", " " + "New Word")
Try this regex (^.+)b(.+$)
Example (Replace the last b character)
System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", "$1$2"));
精彩评论