[英]Escape double quotes in a C# string
我正在尝试像这样在我的字符串中转义\\
和"
:
text.Replace("\\", "\\\\").Replace("\"", "\\\"");
但是text
的结果,
arash "moeen"
结果是
arash \\\"moeen\\\"
我怎样才能解决这个问题?
只需将@
用于逐字文字字符串。
text.Replace(@"this", @"that");
例子:
text.Replace(@"\", @"\\").Replace(@"""", @"\""");
如果我理解正确,首先, text = arash "moeen"
不是有效的常规字符串文字。 我假设你的字符串像;
string s = "text = arash \"moeen\"";
打印为
text = arash "moeen" // I think this is your original string.
由于你arash \\"moeen\\"
结果,你只需要在你的字符串中用\\"
替换你的"
;
string s = "text = arash \"moeen\"";
s = s.Replace("\"", "\\\"");
所以你的结果将是arash \\"moeen\\"
更多信息:转义序列
如果这是一个 JSON 字符串,我的答案将无效:-p
你的作业代码是什么?
它应该是
var text = @"arash ""moeen""";
string text = @"arash ""moeen""";
MessageBox.Show(text.Replace(@"\", @"\\").Replace(@"""", @"\"""));
假设你有这样的字符串
string test = "He said to me, \"Hello World\". How are you?";
在任何一种情况下,字符串都没有改变 - 其中只有一个转义的 " 。这只是告诉 C# 字符是字符串的一部分而不是字符串终止符的一种方式。
当你想要arash \\"moeen\\"
arash "moeen"
,做text.Replace(", \\");
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.