Replace Last Occurrence of a character in a string

Mahe picture Mahe · May 21, 2013 · Viewed 88.5k times · Source

I am having a string like this

"Position, fix, dial"

I want to replace the last double quote(") with escape double quote(\")

The result of the string is to be

"Position, fix, dial\"

How can I do this. I am aware of replacing the first occurrence of the string. but don't know how to replace the last occurrence of a string

Answer

Bernhard Barker picture Bernhard Barker · May 21, 2013

This should work:

String replaceLast(String string, String substring, String replacement)
{
  int index = string.lastIndexOf(substring);
  if (index == -1)
    return string;
  return string.substring(0, index) + replacement
          + string.substring(index+substring.length());
}

This:

System.out.println(replaceLast("\"Position, fix, dial\"", "\"", "\\\""));

Prints:

"Position, fix, dial\"

Test.