C#两个双引号

12
我想在C#中打印两个双引号作为输出。如何做到这一点?
我是说输出应该是:"" Hello World ""
11个回答

22
Console.WriteLine("\"\" Hello world \"\"");

或者

Console.WriteLine(@""""" Hello world """"");

2
啊,你刚刚赢了我。这么简单的问题,却有那么多错误的答案! - Mr Lister
4个双引号("""")是什么意思? - monish001
2
@Monish "" 是在 @"..." 字面字符串中的一个双引号。 - Balazs Tihanyi

7
如果你想在字符串中使用双引号,你需要用 \ 来转义它们。
例如:
string foo = "here is a \"quote\" character";

如果你想字面上输出"" Hello World "",那么你需要:

string helloWorld = "\"\" Hello World \"\"";
output(helloWorld);

(其中输出是您用于输出的任何方法)
注:该句为一个代码注释,表示"输出"指的是代码中使用的输出方法。

2

一种方法是转义引号:

var greeting = "\"Hello World\"";

2
您可以使用@输出,这将自动转义特殊字符。
string output = "\"\" Hello World \"\"";

string output = @""""" Hello World """"";

2

当你想使用特殊字符时,如果该字符存在于你的语言中,在该字符前添加\即可使该特殊字符作为字符串处理。在你的情况下,请像这样使用。

\"Hello word\"

输出
 "Hello word"

2
如果您经常需要执行此操作,并希望代码更加简洁,您可能会喜欢拥有一个扩展方法来实现此功能。
这是非常明显的代码,但我认为抓住它并使您节省时间是很有用的。
  /// <summary>
    /// Put a string between double quotes.
    /// </summary>
    /// <param name="value">Value to be put between double quotes ex: foo</param>
    /// <returns>double quoted string ex: "foo"</returns>
    public static string PutIntoQuotes(this string value)
    {
        return "\"" + value + "\"";
    }

那么你可以在任何你想要的字符串上调用foo.PutIntoQuotes()或"foo".PutIntoQuotes()。

希望这有所帮助。


1

转义它们:

Console.WriteLine("\"Hello world\"");

1

在双引号前使用反斜杠:\"


1
Console.WriteLine("\"\"Hello world\"\"");

反斜杠('\')字符位于任何“特殊”字符之前,否则该字符会被解释为代码的一部分而不是要输出的字符串的一部分。这是一种告诉编译器将其视为字符串的一部分而不是C#语言中具有某种目的的字符的方法。

0

在“普通”双引号之前使用@字符将导致打印出这些双引号之间的每个特殊字符

string foo = @"foo "bar"";

1
在一个逐字字符串(@"")中,您需要使用2个引号字符,即""。你现在的写法是错误的。原帖作者想要的应该是类似这样的:@""""" Hello World """"" - George Duckett
确实。双引号实际上是“@string”中唯一的特殊字符(我忘了它们的真正名称)。这是因为显然 "@" 是字符串的终止符,因此如果要使用它来不终止字符串,则需要转义。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接