GurdeepS
GurdeepS

Reputation: 67223

Writing a string which contains " "

I have a string from an xml document:

<title type="html">

Is there a way for me to write this string like "<title type="html">"? I've had similar problems writing javascript as a string but I did see some solutions in the past (which I can't remember)?

Thanks

Upvotes: 10

Views: 40588

Answers (6)

Eoin Campbell
Eoin Campbell

Reputation: 44278

You need to escape your double quotes..

string blah = "<title type=\"html\">";

OR

string blah = @"<title type=""html"">";

Alternatively you could use single quotes in your tag, which will serve the same purpose.

string blah = "<title type='html'>"; 

Upvotes: 28

gub
gub

Reputation: 5229

Escape:

var str = "<font color=\"red\">;";

(Edit: forgot to put proper html chars in!)

Or in javascript you can use single quotes to contain one with doubles:

var str = '<font color="red">';

Upvotes: 3

jay_t55
jay_t55

Reputation: 11652

string jason = "This string contains a \"";

Upvotes: 1

SLaks
SLaks

Reputation: 887509

If you're making a large string with a lot of XML, one approach would be to write

var str = @"<tag attribute=`value`><SubTag OtherAttribute=`OtherValue` /></tag>".Replace('`', '"');

Beware that this will be less efficient at runtime, because of the call to Replace().

The best way to handle this is might be to put the markup in a separate text file and embed it in a ResX file. That would allow you to write Properties.Resources.Markup.

Upvotes: 1

Simon P Stevens
Simon P Stevens

Reputation: 27499

You can escape quotes in a string using a \

String s = "this is my \"data\" in the string";

Upvotes: 25

Daren Thomas
Daren Thomas

Reputation: 70324

You can also write it like this:

string f = @"<font color=""red"">";

Check out msdn on string literals.

Upvotes: 2

Related Questions