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("\"", "\\\"");
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);