Replacing double quote with a single quote

2019-02-21 15:32发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

writer.QuoteChar = '\'';

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



标签: c# replace