Replace the string containing "with"?

How do I replace the string containing "

by \"

?

replace(""","\"")

doesn't work for me.

public static String replaceSpecialCharsForJson(String str){
    return str.replace("'","\'")
              .replace(":","\\:")
              .replace("\"","\"")
              .replace("\r", "\\r")
              .replace("\n", "\\n");
} 

      

+3


source to share


6 answers


You may try:

replace("\"","\\\"")

      



Since both "

and \

are metacharacters, you must avoid them with\

+5


source


Try the following:



replace("\"","\\\"");

      

+1


source


Each forward slash must be escaped as part of a string. So if you want a string to look like "\\"

, your code must contain String s = "\\\\"

. Terrible but true.

The same applies to any other special character that can be interpreted. Quotes and colons inclusive. This means it " \ " "

will look like " \\ \" "

(Added spaces to make individual screens more visible)

+1


source


Using:

str.replace("\"","\\\"")

      

So, you are avoiding the backslash.

0


source


Do you want to

  • replace "

    (correctly screened: \"

    )
  • with \"

    (correctly escaped :) \\\"

    .

Correct call:

replace("\"", "\\\"");

      

0


source


I've tried this way. I don't know how useful this is in your scenario

String oldStr = String.valueOf('"');
String newStr = File.separator.concat(String.valueOf('"'));     
System.out.println(oldStr.replace(String.valueOf('"'),newStr));

      

0


source







All Articles