Getting " when trying to replace a character in string

Kumar Harsh :

I want to replace " from a string with ^.

String str = "hello \"there";
System.out.println(str);
String str1 = str.replaceAll("\"", "^");
System.out.println(str1);
String str2= str1.replaceAll("^", "\"");
System.out.println(str2);

and the output is :

hello "there
hello ^there
"hello ^there

why I am getting extra " in start of string and ^ in between string

I am expecting:

hello "there
tonyhoan :

the replaceAll() method consume a regex for the 1st argument.

the ^ in String str2= str1.replaceAll("^", "\""); will match the starting position within the string. So if you want the ^ char, write \^

Hope this code can help:

String str2= str1.replaceAll("\\^", "\"");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=440680&siteId=1