Replace Last Occurrence of a character in a string

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.


String str = "\"Position, fix, dial\"";
int ind = str.lastIndexOf("\"");
if( ind>=0 )
    str = new StringBuilder(str).replace(ind, ind+1,"\\\"").toString();
System.out.println(str);

Update

 if( ind>=0 )
    str = new StringBuilder(str.length()+1)
                .append(str, 0, ind)
                .append('\\')
                .append(str, ind, str.length())
                .toString();