Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double quote string replace in C#

Tags:

c#

How to replace the below string in C#

Current:

"John K "GEN" Greg" 

The Goal:

 "John K \"GEN\" Greg" 

This is wrong because I'm not escaping it properly:

s = s.Replace(""","\""); 

What is syntax for replacing quotes with \ (slash)?

Any help would be appreciated.

Thanks

like image 499
pal Avatar asked Feb 22 '12 11:02

pal


2 Answers

s = s.Replace("\"", "\\\""); 

or

s = s.Replace(@"""", @"\"""); 

In the first example the " has to be escaped with a backslash as it would otherwise end the string. Likewise, in the replacement string \\ is needed to yield a single backslash by escaping the escape character.

In the second example verbatim string literals are used, they are written as @"...". In those literals no escape sequences are recognized, allowing you to write strings that contain lots of backslashes in a much cleaner way (such as regular expressions). The only escape sequence that works there is "" for a single ".

like image 180
Joey Avatar answered Sep 27 '22 19:09

Joey


You should use a double backslash:

s = s.Replace("\"", "\\\""); 
like image 28
zmbq Avatar answered Sep 27 '22 20:09

zmbq