替换字符串中字符的最后一次出现

我有这样的字符串

"Position, fix, dial" 

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

字符串的结果是

 "Position, fix, dial\" 

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

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

这应该工作:

 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\" 

测试 。

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

 localDir = (dir.endsWith("/")) ? dir.substring(0,dir.lastIndexOf("/")) : dir; 
 String docId = "918e07,454f_id,did"; StringBuffer buffer = new StringBuffer(docId); docId = buffer.reverse().toString().replaceFirst(",",";"); docId = new StringBuffer(docId).reverse().toString();