user2058253
user2058253

Reputation: 301

Replacing double quote with a single quote

I have the following string in c#:

string ptFirstName = tboxFirstName.Text;

ptFirstName returns: "John"

I wish to convert this to 'John'

I have tried numerous variations of the following, but I am never able to replace double quotes with single quotes:

ptFirstName.Replace("\"", "'");

Can anybody enlighten me?

My goal is to write this to an XML file:

writer.WriteAttributeString("first",ptFirstName);   // where ptFirstName is 'John' in single quotes.

Upvotes: 14

Views: 35388

Answers (3)

shalongbus
shalongbus

Reputation: 336

writer.QuoteChar = '\'';

See http://msdn.microsoft.com/en-ca/library/system.xml.xmltextwriter.quotechar.aspx for details.

Upvotes: 0

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241430

I will guess that you didn't type "John" into the textbox, but just John and you are seeing quotes around the string when you set a breakpoint and are looking at the variable in visual studio?

If so, then realize that the quotes there are not part of the string, but just indicating to you that the value is a string. They are added by the debugger. If you were to do:

Console.WriteLine(ptFirstName);

you would not see the quotes.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The reason

ptFirstName.Replace("\"", "'");

does not work is that string is immutable. You need to use

ptFirstName = ptFirstName.Replace("\"", "'");

instead. Here is a demo on ideone.

Upvotes: 20

Related Questions