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

末鹿安然 提交于 2019-11-26 17:23:01

问题


This question already has an answer here:

  • Replace last part of string 11 answers

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


回答1:


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();



回答2:


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.




回答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;



回答4:


String docId = "918e07,454f_id,did";
StringBuffer buffer = new StringBuffer(docId);
docId = buffer.reverse().toString().replaceFirst(",",";");
docId = new StringBuffer(docId).reverse().toString();


来源:https://stackoverflow.com/questions/16665387/replace-last-occurrence-of-a-character-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!