0

I have string like this:

Hello &f are &f you &f here?

And I want to replace only last &f with "" (by last I mean third one, which is near "here". I tried something like this:

"Hello &f are &f you &f here?".replaceAll(".&f", "")

But it doesn't work, so could someone help me?

Luis
  • 75
  • 6
  • possible duplicate http://stackoverflow.com/questions/16665387/replace-last-occurrence-of-a-character-in-a-string – Vamshi Jan 30 '14 at 18:09

3 Answers3

1
    String s = "Hello &f are &f you &f here?";
    s = s.substring(0,s.lastIndexOf("&f")) + s.substring(s.lastIndexOf("&f")+3);
    System.out.println("s = " + s); // prints: s = Hello &f are &f you here?
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
1

Use this:

(.*)&f

And replace with the backreference $1. (Or is it \1 in Java?)

http://regex101.com/r/qG0fM9

brandonscript
  • 68,675
  • 32
  • 163
  • 220
1

Can also be done with StringBuilder.reverse()

String str1 = "Hello &f are &f you &f here ?";
String temp = new StringBuilder(str1).reverse().toString().replaceFirst("f&", "");
String rslt = new StringBuilder(temp).reverse().toString();
System.out.println(rslt);

Steps:

  1. Reverse the String using StringBuffer
  2. Replace first f& with the help of String.replaceFirst()
  3. Then again reverse that String.

Output:

Hello &f are &f you  here ?
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55