Double quote string replace in C#

后端 未结 6 622
野性不改
野性不改 2020-12-05 09:15

How to replace the below string in C#

Current:

\"John K \"GEN\" Greg\"

The Goal:

 \"John K \\\"GEN\\\" Greg\"
         


        
6条回答
  •  感动是毒
    2020-12-05 09:53

    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 ".

提交回复
热议问题