25

我有这样的字符串

"Position, fix, dial"

我想用转义双引号(\“)替换最后一个双引号(“)

字符串的结果是

"Position, fix, dial\"

我怎样才能做到这一点。我知道替换第一次出现的字符串。但不知道如何替换最后出现的字符串

4

4 回答 4

61

这应该有效:

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

这个:

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

印刷:

"Position, fix, dial\"

测试

于 2013-05-21T08:37:41.077 回答
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);

更新

 if( ind>=0 )
    str = new StringBuilder(str.length()+1)
                .append(str, 0, ind)
                .append('\\')
                .append(str, ind, str.length())
                .toString();
于 2013-05-21T08:36:21.750 回答
2

如果您只想删除 las 字符(如果有的话),这是一种单行方法。我将它用于目录。

localDir = (dir.endsWith("/")) ? dir.substring(0,dir.lastIndexOf("/")) : dir;
于 2015-07-31T15:54:27.463 回答
2
String docId = "918e07,454f_id,did";
StringBuffer buffer = new StringBuffer(docId);
docId = buffer.reverse().toString().replaceFirst(",",";");
docId = new StringBuffer(docId).reverse().toString();
于 2016-05-06T07:10:56.633 回答