user1899050
user1899050

Reputation: 31

How can i replace " with \" in C#

Input String is "How are you" Expected output \"How are you\"

Due to combination of DoubleQuote and escape sequence I am not able to replace the string in the required format.

Please can someone provide me the code snippet for doing this.

I have tried below does not work

myString.Replace(""","\"");

Upvotes: 1

Views: 97

Answers (4)

Muhammad Umar
Muhammad Umar

Reputation: 3781

string myString = "\"How are you\"";  
myString = myString.Replace("\"", "\\\"");

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

Escape your backslash

myString.Replace("\"","\\\"");

This:

"\\\"" 

produces this:

\"

And also you should escape your double quote in first parameter.

And you can use verbatim strings,but there is a weird case about double quote, instead of \" you should use two double quotes "" to escepe your charachter:

myString.Replace(@"""",@"\""");

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67195

Both " and \ have special meaning within a string literal and must be escaped with \.

So something like this:

myString.Replace("\"","\\\"");

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460098

Yes, that looks a little bit weird, you need to escape both:

string test = "\"How are you\"";
test = test.Replace("\"", "\\\"");

Upvotes: 4

Related Questions