Let's say I have a string
string myWord="AAAAA";
I want to replace "AA" with "BB", but only the last occurrence, like so:
"AAABB"
Neither string.replace() nor string.replaceFirst() would do the job. Is there a string.replaceLast()? And, If not, will there ever be one or is there an alternative also working with regexes?
Use the String. replace() method to replace the last character in a string, e.g. const replaced = str.
Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);
Using replace() function. In Python, the string class provides a function replace(), and it helps to replace all the occurrences of a substring with another substring. We can use that to replace only the last occurrence of a substring in a string.
The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)
Find the index of the last occurrence of the substring.
String myWord = "AAAAAasdas";
String toReplace = "AA";
String replacement = "BBB";
int start = myWord.lastIndexOf(toReplace);
Create a StringBuilder
(you can just concatenate Strings if you wanted to).
StringBuilder builder = new StringBuilder();
Append the part before the last occurrence.
builder.append(myWord.substring(0, start));
Append the String
you want to use as a replacement.
builder.append(replacement);
Append the part after the last occurrence from the original `String.
builder.append(myWord.substring(start + toReplace.length()));
And you're done.
System.out.println(builder);
You can do this:
myWord = myWord.replaceAll("AA$","BB");
$
means at the last.
Just get the last index and do an in place replacement of the expression with what you want to replace.
myWord
is the original word sayAABDCAADEF
. sourceWord
is what you want to replace, say AA
targetWord
is what you want to replace it with say BB
.
StringBuilder strb=new StringBuilder(myWord);
int index=strb.lastIndexOf(sourceWord);
strb.replace(index,sourceWord.length()+index,targetWord);
return strb.toString();
This is useful when you want to just replace strings with Strings.A better way to do it is to use Pattern matcher and find the last matching index. Take as substring from that index, use the replace function there and then add it back to the original String. This will help you to replace regular expressions as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With