0

I want to replace \ with " symbol using C# code.Here i am writing code for it.

string str=jsonstringdata.Replace("\"",""");

But it showing error obviously.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
user3643469
  • 15
  • 1
  • 7

6 Answers6

4

Use either single-quoted characters, @verbatim strings, or properly escape the characters:

str.Replace('\\', '"')
str.Replace(@"\", @"""")
str.Replace("\\", "\"")

Explanations:

  1. Single characters are delimited with single-quotes characters '. The same backslash-escape rules from literal strings apply to literal characters, except that you can specify a double-quote directly (i.e. '"' instead of '\"').
  2. Verbatim strings in C# do not have backslash escapes (i.e. backslashes are interpreted literally) making them useful for file-paths. Verbatim strings do allow you to escape double-quote characters by doubling them up, like in VB's strings, e.g. @"""" is a string containing a single double-quote character, similarly @"foo""bar" is a string with a single double-quote between "foo" and "bar".
  3. Otherwise, with normal strings, use backslash to escape any special characters and backslash itself.
Dai
  • 141,631
  • 28
  • 261
  • 374
3

this should do it - need to escape the correct characters.

string str = jsonstringdata.Replace("\\","\"");
user1666620
  • 4,800
  • 18
  • 27
0
string str= jsonstringdata.Replace("\\","\"");
André Snede
  • 9,899
  • 7
  • 43
  • 67
0

Characters must be escaped correctly. Look here for some more knowledge on JavaScript strings and how to escape the correct characters.

string result = yourString.Replace("\\","\"");

Charles
  • 26
  • 1
  • 2
0

You need to handle escape sequences correctly. Use a \\ for finding \ and \" for replacing each \ with ". See the following link http://msdn.microsoft.com/en-us/library/aa691087(v=vs.71).aspx

string input = @"\a\\\\";
char replaceble = '\\';
char replacingChar = '\"';
var output = input.Replace(replaceble, replacingChar);
aeje
  • 239
  • 1
  • 9
0

You need to escape the slash and quote characters.

var jsonStringData = "{ Hello\\World }";

string str = jsonStringData.Replace("\\", "\"");

// output of str = { Hello"World }
Adam
  • 4,590
  • 10
  • 51
  • 84