19

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?

Magnus
  • 1,550
  • 4
  • 14
  • 33

7 Answers7

35

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);
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
33

You can do this:

myWord = myWord.replaceAll("AA$","BB");

$ means at the last.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
5

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Biswajit_86
  • 3,661
  • 2
  • 22
  • 36
2
String string = "AAAAA";
String reverse = new StringBuffer(string).reverse().toString();
reverse = reverse.replaceFirst(...) // you need to reverse needle and replacement string aswell!
string = new StringBuffer(reverse).reverse().toString();
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
  • 3
    Won't this work only if the string to replace and the replacement are palindromes? Also, Strings are immutable so you have to do something with the `replaceFirst`. – Sotirios Delimanolis Apr 27 '14 at 16:54
  • 1
    True, you need to reverse replacement string aswell. – Flash Thunder Apr 27 '14 at 17:02
  • You still need to do something with the result of the `reverse.replaceFirst()` call, such as reassign it to `reverse`. – Sotirios Delimanolis Apr 27 '14 at 17:08
  • (Comment is from @Biswajit_86) You need to reverse both the source and target expressions for this to work. So if you want to replace AB in ABABAAB with CA, then you steps would be 1. Reverse ABABAAB 2. Reverse source string AB to BA 3. Reverse target CA to AC 4. Now use the replacefirst 5. Then reverse the target string – cf- Apr 27 '14 at 18:06
  • Nasty, but works "I FROM want to FROM this" `String originalString = "I FROM want to FROM this"; String stringReverse = String.valueOf(new StringBuffer(originalString).reverse()).replaceFirst("MORF","OT"); originalString= String.valueOf(new StringBuffer(stringReverse ).reverse()); System.out.println(originalString);` "I FROM want to TO this" – Joviano Dias Mar 29 '23 at 18:15
1

It seems like there could be a regex answer to this.

I initially was trying to solve this through regex, but could not solve for situations like 'AAAzzA'.

So I came up with this answer below, which can handle both 'AAAAA' and 'AAAzzA'. This may not be the best answer, but I guess it works.

The basic idea is to find the last index of 'AA' occurrence and split string by that index:

String myWord = "AAAAAzzA";
String source = "AA";
String target = "BB";
int lastIndex = -1;
if ((lastIndex = myWord.lastIndexOf(source)) >= 0) {
    String f = myWord.substring(0, lastIndex);
    String b = myWord.substring(lastIndex + target.length() >= myWord
            .length() ? myWord.length() : lastIndex + target.length(),
            myWord.length());
    myWord = f + target + b;
}
System.out.println(myWord);
wns349
  • 1,266
  • 1
  • 10
  • 20
-2
myWord=myWord.replaceAll("AA(?!A)","BB");
Anirudha
  • 32,393
  • 7
  • 68
  • 89
-3

You can do this with String#subtring

myWord= myWord.substring(0, myWord.length() - 2) + "BB";
Asif Bhutto
  • 3,916
  • 1
  • 24
  • 21