简体   繁体   中英

Escape double quotes in a C# string

I'm trying to escape \\ and " in my string like this:

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

But the result for text ,

arash "moeen"

turns out as

arash \\\"moeen\\\"

How can I fix this?

Just use @ for verbatim literal strings.

text.Replace(@"this", @"that");

Example:

text.Replace(@"\", @"\\").Replace(@"""", @"\""");

If I understand correctly, first of all, text = arash "moeen" is not a valid regular string literal. I assume your string like;

string s = "text = arash \"moeen\"";

which is printed as

text = arash "moeen" // I think this is your original string.

Since you arash \\"moeen\\" as a result, you just need to replace your " with \\" in your string like;

string s = "text = arash \"moeen\"";
s = s.Replace("\"", "\\\"");

So your result will be arash \\"moeen\\"

More information: Escape Sequences

If this is a JSON string, my answer will be invalid :-p

What is your assignment's code?

It should be

var text = @"arash ""moeen""";
string text = @"arash ""moeen""";
MessageBox.Show(text.Replace(@"\", @"\\").Replace(@"""", @"\"""));

Suppose you have string like this

string test = "He said to me, \"Hello World\". How are you?";

The string has not changed in either case - there is a single escaped " in it. This is just a way to tell C# that the character is part of the string and not a string terminator.

When you want arash \\"moeen\\" from arash "moeen" , do text.Replace(", \\"); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM