我有一个这样的字符串变量:

string title = string.empty;

我必须在双引号内的div中显示传递给它的任何内容。我写过这样的东西:

...
...
<div>"+ title +@"</div>
...
...

我怎么在这里加双引号?这样它就会像这样显示:

"How to add double quotes"

当前回答

在c#中,你可以使用:

 string1 = @"Your ""Text"" Here";
 string2 = "Your \"Text\" Here";

其他回答

你可以用&quot;而不是“。”浏览器将正确地显示它。

在双引号前加一个反斜杠(\)。这应该有用。

如果你必须经常这样做,并且你想让代码更干净,你可能会喜欢有一个扩展方法。

这是非常明显的代码,但我仍然认为它可以帮助您节省时间。

  /// <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 AddDoubleQuotes(this string value)
    {
        return "\"" + value + "\"";
    }

然后你可以在你喜欢的每个字符串上调用foo. adddoublequotes()或"foo". adddoublequotes()。

在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 str = """
    "How to add double quotes"
    """;

如果我理解你的问题,也许你可以试试这个:

string title = string.Format("<div>\"{0}\"</div>", "some text");