java 用另一个单引号替换字符串中的单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15017254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace a single quote in a string with another single quote
提问by Vidya
I have a String with single quote. I want to replace the single quote with 2 single quotes. I tried using
我有一个带单引号的字符串。我想用 2 个单引号替换单引号。我尝试使用
String s="Kathleen D'Souza";
s.replaceAll("'","''");
s.replaceAll("\'","\'\'");
s.replace("'","''");
s.replace("\'","\'\'");
But the single quote is not getting replaced with 2 single quotes.
但是单引号不会被 2 个单引号替换。
回答by codeMan
reassign the replaced string to s
将替换的字符串重新分配给 s
String s="Kathleen D'Souza";
s = s.replaceAll("'","''");
回答by Jason
Please try s= "test ' test";
请尝试 s="test'test";
`s.replaceAll("'","\"");` => test " test
`s.replaceAll("'","''");` => test '' test
回答by eze
Note, with the given solutions successive single quotes will be doubled, so Kathleen D''Souza turns into Kathleen D''''Souza. (I've seen users outsmart themselves like this.) If that is something you are concerned about, you can match successive single quotes with:
请注意,对于给定的解决方案,连续的单引号将加倍,因此 Kathleen D''Souza 变成 Kathleen D''''Souza。(我见过用户像这样比自己更聪明。)如果这是您关心的问题,您可以将连续的单引号与以下内容匹配:
s = s.replaceAll("''*","''");
回答by Reimeus
Strings
are immutable. Assign the result of replaceAll
to your String
:
Strings
是不可变的。将结果分配replaceAll
给您的String
:
s = s.replaceAll("'","''");
回答by Achintya Jha
String s="Kathleen D'Souza";
s= s.replace("'", "''");
Try String#replace(). It will replace all occurrence of single ' with double ''.
试试字符串#replace()。它将用双 '' 替换所有出现的单 '。