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

Viewed 669684

I have a string variable such as this:

string title = string.empty;

I have to display the content of whatever is passed to it inside a div within double quotes. I have written something like this:

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

How can I add the double quotes here? So that it will display like:

"How to add double quotes"
20 Answers

You can also include the double quotes into single quotes.

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

If you want to add double quotes to a string that contains dynamic values also. For the same in place of CodeId[i] and CodeName[i] you can put your dynamic values.

data = "Test ID=" + "\"" + CodeId[i] + "\"" + " Name=" + "\"" + CodeName[i] + "\"" + " Type=\"Test\";

You can use $.

Interpolated Strings: Used to construct strings. An interpolated string looks like a template string that contains interpolated expressions. An interpolated string returns a string that replaces the interpolated expressions that it contains with their string representations. This feature is available in C# 6 and later versions.

string commentor = $"<span class=\"fa fa-plus\" aria-hidden=\"true\"> {variable}</span>";

An indirect, but simple to understand alternative to add quotes at start and end of string -

char quote = '"';

string modifiedString = quote + "Original String" + quote;

With C# 11.0 preview you can use Raw String Literals.

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

If you want to add double quotes in HTML

echo "<p>Congratulations, &#8220;" . $variable . "&#8221;!</p>";

Output

Congratulations, "Mr John"!

Start each row with "-" to create a bullet list.

Related