【问题标题】:Escape double quotes in a C# string在 C# 字符串中转义双引号
【发布时间】:2014-09-30 07:35:50
【问题描述】:

我试图在我的字符串中转义 \",如下所示:

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

但是text的结果,

arash "moeen"

结果是

arash \\\"moeen\\\"

我该如何解决这个问题?

【问题讨论】:

  • 什么是 text 开头?您将 \ 替换为 \\ 并将 " 替换为 \"
  • 为什么要逃避它们?
  • text = arash "moeen"
  • 所以你希望你的结果文本变成:arash \"moeen\"?
  • 因为当我解析它时,它们往往会破坏我的 json 字符串。

标签: c# string escaping double-quotes


【解决方案1】:

只需将@ 用于逐字文字字符串。

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

例子:

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

【讨论】:

  • 并使用双引号作为引号:即要获取a "b",请输入@"a ""b"""
  • 那么转义“应该怎么办?.replace(@"\"", @"\\\"") ??
  • 应该是 text.Replace(@"\", @"\\").Replace(@"""", @"\""")
  • 是的,谢谢,但现在替换它后变成 arash \\\"moeen\\\" 然后在我解析它之后,它在我的文本区域中变成 arash \"moeen\"
  • @arashmoeen 好吧,那我不知道你想要什么或者你在处理什么。
【解决方案2】:

如果我理解正确,首先,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\"

更多信息:Escape Sequences

如果这是一个 JSON 字符串,我的答案将是无效的:-p

【讨论】:

  • 是的,它将作为 JSON 字符串的一部分,在我解析它之后,它会在我的 textview 中以 arash \"moeen\" 结尾
【解决方案3】:

你的作业代码是什么?

应该是

var text = @"arash ""moeen""";

【讨论】:

    【解决方案4】:
    string text = @"arash ""moeen""";
    MessageBox.Show(text.Replace(@"\", @"\\").Replace(@"""", @"\"""));
    

    【讨论】:

      【解决方案5】:

      假设你有这样的字符串

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

      在这两种情况下,字符串都没有改变——其中有一个转义的 "。 这只是告诉 C# 字符是字符串的一部分而不是字符串终止符的一种方式。

      【讨论】:

        【解决方案6】:

        当你想要 arash \"moeen\" 来自 arash "moeen" 时,请执行 text.Replace(", \");

        【讨论】:

        • 当你做 string text = "arash "moeen"" 然后 text.Replace(",\");
        • @Sybren 甚至无法编译。 string.Replace 没有重载,它接受一个字符串类型的参数。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-06
        • 2011-02-08
        • 1970-01-01
        相关资源
        最近更新 更多