开发者

replacing escape character with double qoutes in c#

I have the following string in a variable called,

s:

[{\"roleIndex\":0,\"roleID\":\"c1_r0_23\",\"roleName\":\"Chief Executive\"},                       
{\"roleIndex\":1,\"roleID\":\"c1_r1_154\",\"开发者_开发百科roleName\":\"Chief Operator\"}]

and I'm trying to replace \" with " with the following command:

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

but this is not working.

What is the correct syntax in c#?


Try s.ToString().Replace(@"\""", "\"").

The @ tells C# to interpret the string literally and not treat \ as an escape character. "\"" as the second argument uses \ as an escape character to escape the double quotes.

You also don't need to call ToString() if s is already of type string.

Last but not least, don't forget that string replacement is not done in place and will create a new string. If you want to preserve the value, you need to assign it to a variable:

var newString = s.ToString().Replace(@"\""", "\"");
// or s = s.Replace(@"\""", "\"");  if "s" is already a string.


Update

if you have a string containing ", when you view this string in the Visual Studio immediate window it will display it as \". That does not mean that your string contains a backslash! To prove this to yourself, use Console.WriteLine to display the actual value of the string in a console, and you will see that the backslash is not there.

Here's a screenshot showing the backslash in the immediate window when the string contains only a single quote.

replacing escape character with double qoutes in c#

Original answer

Three things:

  • Strings are immutable. Replace doesn't mutate the string - it returns a new string.
  • Do you want to replace a quote "\"" or a backslash followed by a quote "\\\"". If you want the latter, it would be better to use a verbatim string literal so that you can write @"\""" instead.
  • You don't need to call ToString on a string.

Try this:

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

See it on ideone.


Ironically, you need to escape your quote marks and your backslash like so:

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

Otherwise it will cat your strings together and do the same as this (if you could actually use single quotes like this):

s.ToString().Replace('"', "");

(your second string has four quotes... that's why you're not getting a compile error from having """)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜