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?
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(@"""", @"\""");
What is your assignment's code?
It should be
var text = @"arash ""moeen""";
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
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(", \");
.