开发者

Replace double quotes(") [duplicate]

开发者 https://www.devze.com 2023-03-05 15:51 出处:网络
This question already has answers here: replace String with another in java (7 answers) 开发者_JAVA百科Closed 9 years ago.
This question already has answers here: replace String with another in java (7 answers) 开发者_JAVA百科 Closed 9 years ago.

Here my String is looking like :-

sTest = AAAAA"1111

I want to replace double quote to a back ward slash and a double quotes(\")

I need the String Like

sTest = AAAAA\"1111


String escaped = "AAAAA\"1111".replace("\"", "\\\"");
  • API doc for String.replace

(Note that the replaceAll version handles regular expressions and is an overkill for this particular situation.)


string.replace("\"", "\\\"")

You want to replace " with \". Since both " and \ have a specific meaning you must escape them correctly by adding a preceding \ before each one.

So " --> \" and \" --> \\\". And since you want the compiler to understand that this is a String, you need to wrap each string with double-quotes So " --> \" and "\"" --> "\\\"".


Although the other answers are correct for the single situation given, for more complicated situations, you may wish to use StringEscapeUtils.escapeJava(String) from Apache Commons Lang.

String escaped = StringEscapeUtils.escapeJava(string);


System.out.println("AAAAA\"1111".replaceAll("\"", "\\\\\""));
0

精彩评论

暂无评论...
验证码 换一张
取 消