简体   繁体   中英

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM