Reputation: 2896
I have struggled with a simple replace. And need a good solution. Background: It is a xml string encoded with \" and these need to be " to be able to deserialize it with serializer.Deserialize.
I want to replace backslash doublequot with one double quot a string like " \"hello\" " so the string are " "hello" ". The text is long so it is not possible to remove backslash. Thanks for advise. I think it should have been
string s= "\" teetete \"";
string t;
t = s.Replace("\"", @"""");
Upvotes: 5
Views: 10963
Reputation: 1424
It's not clear what you want to do, but it sounds like you have an XML string that contains a double-quote character (being displayed as \"
in the debugger) and you need to replace it with "
to allow the XML parser to understand it. In which case a simple call to .Replace()
may be enough (although I imagine in reality there are edge cases that will need to be resolved with something more complex).
Upvotes: 0
Reputation: 460138
Your sample string doesn't contain any backslashes, you are just using it to mask the double quotes. This contains one backslash at the beginning and one at the end:
string s = "\\\" teetete \\\"";
If you want to replace it with a single double quote:
string t = s.Replace("\\\"", "\"");
You have to look click at the loupe in the debugger to see the real value of a string:
Upvotes: 8
Reputation: 51807
That isn't actually encoded with \"
. That is literally a string whose contents are " teetete "
. In order to display it, or compile the string, you have to escape the quotes, which is why you have:
string s = "\" teetete \"";
A string that has backslash quote in it, i.e. \"
will actually look like this:
string s = "\\\" teetete \\\"";
That is, one set of \\
for a literal \
and \"
for a literal "
. If you want to replace that, then it's almost what you wrote:
string t = s.Replace("\\\"", "\"");
That will convert any \"
in your string to "
, which I'm guessing is what you actually want, unless you're printing it out into some VB.NET code, in which case "\"\""
would be more appropriate.
Upvotes: 0