C# 在字符串中转义双引号

C# 在字符串中转义双引号,c#,string,double-quotes,C#,String,Double Quotes,双引号可以这样转义: string test = @"He said to me, ""Hello World"". How are you?"; 但这涉及到在字符串中添加字符“。是否有C#函数或其他方法来转义双引号,以便不需要更改字符串?否 可以按原样使用逐字字符串文字,也可以使用反斜杠转义“ string test = "He said to me, \"Hello World\" . How are you?"; 字符串在两种情况下都没有改变-其中只有一个转义的“。这只是告诉C#字符是

双引号可以这样转义:

string test = @"He said to me, ""Hello World"". How are you?";
但这涉及到在字符串中添加字符
。是否有C#函数或其他方法来转义双引号,以便不需要更改字符串?

可以按原样使用逐字字符串文字,也可以使用反斜杠转义

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

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

您误解了转义

额外的
字符是字符串文字的一部分;编译器将它们解释为单个


你的字符串的实际值仍然是
他对我说,“你好,世界”。你好吗?
,如果你在运行时打印它,你就会看到。

你可以用反斜杠

string str = "He said to me, \"Hello World\". How are you?";
它打印

He said to me, "Hello World". How are you?
与印刷品完全相同

string str = @"He said to me, ""Hello World"". How are you?";
这是一本书

仍然是字符串的一部分


您可以查看Jon Skeet的文章以了解更多信息。

请解释您的问题。你说:

但这涉及到在字符串中添加“字符”

这是什么问题?您不能键入
string foo=“foo”bar”“;
,因为这将调用编译错误。至于添加部分,以字符串大小表示,这是不正确的:

@"""".Length == 1

"\"".Length == 1
在C#中,可以使用反斜杠在字符串中添加特殊字符。 例如,要放置
,您需要编写
\”
。 您可以使用反斜杠书写许多字符:

用其他字符反斜杠

  \0 nul character
  \a Bell (alert)
  \b Backspace
  \f Formfeed
  \n New line
  \r Carriage return
  \t Horizontal tab
  \v Vertical tab
  \' Single quotation mark
  \" Double quotation mark
  \\ Backslash
任何数字字符替换:

  \xh to \xhhhh, or \uhhhh - Unicode character in hexadecimal notation (\x has variable digits, \u has 4 digits)
  \Uhhhhhhhh - Unicode surrogate pair (8 hex digits, 2 characters)
在C#中,在字符串中嵌入引号至少有4种方法:

  • 带反斜杠的转义引号
  • 在字符串前面加@并使用双引号
  • 使用相应的ASCII字符
  • 使用十六进制Unicode字符

  • 有关详细说明,请参阅此部分。

    C#6中值得一提的另一件事是:$插值字符串可以与@一起使用

    例如:

    string helloWorld = @"""Hello World""";
    string test = $"He said to me, {helloWorld}. How are you?";
    

    检查正在运行的代码


    可以查看对插值的引用!

    您可以这样使用“Hello World”,结果是什么?”“变成”一个文本字符串。C/C++的类似问题(因为这可能是搜索引擎中最热门的问题):相关:超级:)工作良好如果您在这里总结(通过编辑您的答案)会更好-因为链路可能随时中断。例如,“使用相应的ASCII字符”的确切含义是什么?它在源代码中到底是如何编码的?您可以为这四种方法中的每一种提供一个或多个(很棒的)代码示例。这对哪个C版本有效?你能提供一些参考资料吗?请回答,而不是在这里的评论(没有“编辑:”,“更新:”,或类似的-答案应该像今天写的一样出现)。
    string helloWorld = "Hello World";
    string test = $@"He said to me, ""{helloWorld}"". How are you?";