Pregunta

I have a string:

var a = "some text \"";

I want to replace \" with ".

a.Replace("\"", '"'); => The best overloaded method match for 'string.Replace(string, string)' has some invalid arguments

a.Replace("\"", """); => Newline in constant

finally I want to obtain "some text"

¿Fue útil?

Solución

You need to escape your string, you are looking for:

a.Replace("\\\"", "\"");

That should do it!

NOTE

Please note - just calling replace creates a NEW STRING VALUE it does not edit the original string. If you want to use this string you can do the replace inline or you can assign back to the original value like so:

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

That could also be another issue you are having!

Otros consejos

You seem to be confused by C#'s escaping rules. The literal "some text \"" has the value some text ". If you look at this string in the VS debugger, it will show the C# literal that produces the value: "some text \"". If you print it, you'll see its value is actually some text ".

If the value is actually some text \", which could be represented by "some text \\\"" or @"some text \""", then what you really want is this:

var b = a.Replace("\\\"", "\"");

I suspect that your string is actually already what you want, though: some text "

You can use verbatim strings introduced with @. In verbatim strings double quotes are escaped by doubling them and the backslashes don't work as escape characters any more:

string result = a.Replace(@"\""", @""""); 

Compared to normal strings, you still have to escape the double quote ("), but not the backslash (\).

Of course you can combine both solutions:

string result = a.Replace(@"\""", "\""); 

See also: What character escape sequences are available?

'\' This will treated as escape character in C# you need to use double quote to replace it with. see below snippet

string afterreplace = txtBox1.Text.Replace("\\\"", "\"");

You need some escaping! Use this:

a.Replace("\\\"", "\"");
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top