双引号可以像这样转义:

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

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


当前回答

在c# 11.0预览版中,您可以使用原始字符串字面值。

Raw string literals are a new format for string literals. Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (""") characters. It ends with the same number of double-quote characters. Typically, a raw string literal uses three double quotes on a single line to start the string, and three double quotes on a separate line to end the string.

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

其他回答

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

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

详细说明请参考本文件。

No.

要么像您所拥有的那样使用逐字串字面量,要么转义“using反斜杠”。

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

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

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

例子:

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

Or

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

在这里检查运行代码!

在这里查看插值的参考!

你误解了逃跑。

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

你的字符串的实际值仍然是他对我说,“Hello World”。你好吗?,就像你在运行时打印它时看到的那样。

在c# 11.0预览版中,您可以使用原始字符串字面值。

Raw string literals are a new format for string literals. Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (""") characters. It ends with the same number of double-quote characters. Typically, a raw string literal uses three double quotes on a single line to start the string, and three double quotes on a separate line to end the string.

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