How can I add double quotes to a string that is inside a variable?

Solution 1:

You need to escape them by doubling them (verbatim string literal):

string str = @"""How to add doublequotes""";

Or with a normal string literal you escape them with a \:

string str = "\"How to add doublequotes\"";

Solution 2:

So you are essentially asking how to store doublequotes within a string variable? Two solutions for that:

var string1 = @"""inside quotes""";
var string2 = "\"inside quotes\"";

In order to perhaps make it a bit more clear what happens:

var string1 = @"before ""inside"" after";
var string2 = "before \"inside\" after";

Solution 3:

If you have to do this often and you would like this to be cleaner in code, you might like to have an extension method for this.

This is really obvious code, but still I think it can be useful to grab it and make you save time.

  /// <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 + "\"";
    }

Then you may call foo.AddDoubleQuotes() or "foo".AddDoubleQuotes(), on every string you like.

Solution 4:

If I understand your question properly, maybe you can try this:

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

Solution 5:

You can also include the double quotes into single quotes.

string str = '"' + "How to add doublequotes" + '"';