25

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

tchrist
  • 78,834
  • 30
  • 123
  • 180
Mahe
  • 2,707
  • 13
  • 50
  • 69

4 Answers4

61

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.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
44
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();
yavuzkavus
  • 1,268
  • 11
  • 17
  • Just asking. Why not like this? `String str = "\"Position, fix, dial\""; str.replaceAll("[\"]\\Z", "\""); System.out.println(str);` – Dudeist Nov 05 '14 at 23:47
  • yes, you can use something like **str = str.replaceAll("[\"]\\Z", "\\\\\"")**. But it will replace the last quot at the end of input. it wont work for < **"Position, fix, dial" again** >. – yavuzkavus Nov 06 '14 at 13:44
  • 2
    @Dudeist because that's much less readable. – Patrick Jul 20 '15 at 04:25
3

If you only want to remove the las character (in case there is one) this is a one line method. I use this for directories.

localDir = (dir.endsWith("/")) ? dir.substring(0,dir.lastIndexOf("/")) : dir;
juliangonzalez
  • 4,231
  • 2
  • 37
  • 47
2
String docId = "918e07,454f_id,did";
StringBuffer buffer = new StringBuffer(docId);
docId = buffer.reverse().toString().replaceFirst(",",";");
docId = new StringBuffer(docId).reverse().toString();
Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
user2578871
  • 820
  • 6
  • 5