转义字符串中的双引号

双引号可以像这样转义:

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

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

504453 次浏览

不。

要么像你所拥有的那样使用逐字串字面量,要么使用反斜杠转义"

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

在这两种情况下,字符串都没有改变——其中只有一个逃了出来 "。这只是告诉c#字符是字符串的一部分,而不是字符串结束符的一种方式。

你误解了逃跑。

额外的"字符是字符串字面量的一部分;它们被编译器解释为 "

字符串的实际值仍然是He said to me, "Hello World". How are you?,就像你在运行时打印它时看到的那样。

你可以用两种方式使用反斜杠:

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中的字符串文章了解更多信息。

请解释你的问题。你说:

但这涉及到增加个性”;到字符串。

这是什么问题?你不能输入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#中,至少有四种方法可以在字符串中嵌入引号:

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

详细说明请参考这个文档

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

检查运行代码在这里!

查看对插值在这里的引用!

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

c# 11.0预览中,你可以使用原始字符串字面值

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

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