转义字符串中的双引号

问题描述 投票:0回答:9

双引号可以这样转义:

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

但这涉及到将字符

"
添加到字符串中。是否有 C# 函数或其他方法来转义双引号,以便不需要更改字符串?

c# string double-quotes
9个回答
357
投票

是的,您可以使用反斜杠转义

"

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

否则你必须使用逐字字符串文字。

在这两种情况下,字符串都没有改变 - 其中有一个 escaped

"
。这只是告诉 C# 该字符是字符串的一部分而不是字符串终止符的一种方式。


154
投票

您可以以任何一种方式使用反斜杠:

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?";

这是一个

DEMO

"
仍然是字符串的一部分。

您可以查看 Jon Skeet 的 C# 和 .NET 中的字符串文章以获取更多信息。


27
投票

在 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)

19
投票

C# 6 中另一件值得一提的事情是插值字符串可以与

@
一起使用。

示例:

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

或者

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

检查运行代码这里

查看插值参考这里


16
投票

2022 年更新: 以前答案是“否”。但是,C#11 引入了一项称为“原始字符串文字”的新功能。引用微软文档:

从 C# 11 开始,您可以使用原始字符串文字更轻松地创建多行字符串,或使用任何需要转义序列的字符。原始字符串文字消除了使用转义序列的需要。您可以编写字符串,包括空格格式,以及您希望它在输出中显示的方式。”

来源:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#raw-string-literals

示例: 因此,使用原始示例,您可以执行此操作(请注意,原始字符串文字始终以三个或更多引号开头):

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

8
投票

你误会逃跑了。

额外的

"
字符是字符串文字的一部分;它们被编译器解释为 single
"

字符串的实际值仍然是

He said to me, "Hello World". How are you?
,如果您在运行时打印它,您会看到这一点。


6
投票

请解释您的问题。你说:

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

这是什么问题?您不能输入

string foo = "Foo"bar"";
,因为这会引发编译错误。至于 adding 部分,从字符串大小的角度来看,这是不正确的:

@"""".Length == 1

"\"".Length == 1

6
投票

C# 11.0 预览中,您可以使用 原始字符串文字

原始字符串文字是字符串文字的一种新格式。原始字符串文字可以包含任意文本,包括空格、换行符、嵌入引号和其他特殊字符,而无需转义序列。原始字符串文字至少以三个双引号 (""") 字符开头。它以相同数量的双引号字符结尾。通常,原始字符串文字在单行上使用三个双引号来启动字符串,并在单独的行上使用三个双引号来结束字符串。

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

1
投票

在 C# 中,至少有四种方法可以在字符串中嵌入引号:

  1. 用反斜杠转义引号
  2. 在字符串前面加上
    @
    并使用双引号
  3. 使用对应的ASCII字符
  4. 使用十六进制 Unicode 字符

详细说明请参阅此文档

© www.soinside.com 2019 - 2024. All rights reserved.