Mah*_*ahe 22 java string replace last-occurrence
我有这样的字符串
"Position, fix, dial"
Run Code Online (Sandbox Code Playgroud)
我想用转义双引号(\")替换最后一个双引号(")
字符串的结果是
"Position, fix, dial\"
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点.我知道替换第一次出现的字符串.但不知道如何替换最后一次出现的字符串
Duk*_*ing 54
这应该工作:
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());
}
Run Code Online (Sandbox Code Playgroud)
这个:
System.out.println(replaceLast("\"Position, fix, dial\"", "\"", "\\\""));
Run Code Online (Sandbox Code Playgroud)
打印:
"Position, fix, dial\"
Run Code Online (Sandbox Code Playgroud)
试验.
yav*_*vus 41
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);
Run Code Online (Sandbox Code Playgroud)