Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Last Occurrence of a character in a string [duplicate]

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

like image 787
Mahe Avatar asked May 21 '13 08:05

Mahe


3 Answers

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.

like image 167
Bernhard Barker Avatar answered Oct 20 '22 03:10

Bernhard Barker


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();
like image 45
yavuzkavus Avatar answered Oct 20 '22 03:10

yavuzkavus


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;
like image 29
juliangonzalez Avatar answered Oct 20 '22 01:10

juliangonzalez