0
String mp ="\"sameer\\\"raj\"";

I want sameerraj as out put i tried following but no luck.

mp = mp.replace("\"", "");

mp=mp.replaceAll("\\\\", "");

please help me out.

4
  • 4
    mp = mp.replace("\"", ""); does work. It removes \" from your string. If you want to remove \\ as well, you can also do mp = mp.replace("\\",""); Commented Sep 28, 2018 at 11:06
  • 1
    What about mp = mp.replace("\"", "").replace("\\", "") Commented Sep 28, 2018 at 11:09
  • i got this out put sameer\raj Commented Sep 28, 2018 at 11:09
  • 1
    I'm getting your output sameerraj with your code? Commented Sep 28, 2018 at 11:13

4 Answers 4

1

If you want to replace it using regex,then you can use replaceAll

In order to replace ",you need to use \ to escape it,so it will be replaceAll("\"", "")

In order to replace \,you need to use \ to escape itself,but since \ is a special character in regex,you need to use \ to escape it again,so need to use 4 \ in total,which is replaceAll("\\\\", "")

System.out.println(mp.replaceAll("\\\\", "").replaceAll("\"", ""));

output:

sameerraj
Sign up to request clarification or add additional context in comments.

2 Comments

I'm affraid there is a little mistake. replace() function will replace all the occurrences of the given input. replaceAll() function is intended for regular expressions.
@Romansko you are right,thank you, the OP can choose other answer as accepted
1

If you want to change "\"sameer\\\"raj\" to "sameerraj", there are two characters you want to remove: \" and \\.

The easiest way to remove them is with replace.

mp = mp.replace("\"", "").replace("\\","");

You don't need replaceAll, because you don't need to use a regular expression.

Comments

1

To remove \" you need to use escape characters for both of the characters.

Based on your example, this would do the trick:

String mp ="\"sameer\\\"raj\"";
mp = mp.replace("\"", "");
mp = mp.replace("\\", "");

(mp = mp.replace("\"", "").replace("\\", ""); would work the same since these functions return a string.)

If you want to remove \" as a sequental block, you would type:

mp = mp.replace("\\\"", "");

The function will search for a substrings of \" and replace them with empty strings.

replace() function will replace all the occurrences of a given input. replaceAll() function is intended for Regex.

You can read about the differences between replace() and replaceAll() here: Difference between String replace() and replaceAll()

Comments

0

That will give you output sameerraj

String mp ="\"sameer\\\"raj\"";
String r = mp.replace("\\\"","");
String doe=r.replace("\"","");

System.out.println(doe);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.