C# 用单引号代替双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15456645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing double quote with a single quote
提问by user2058253
I have the following string in c#:
我在 C# 中有以下字符串:
string ptFirstName = tboxFirstName.Text;
ptFirstName
returns: "John"
ptFirstName
返回: "John"
I wish to convert this to 'John'
我希望将其转换为 '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:
我的目标是将其写入 XML 文件:
writer.WriteAttributeString("first",ptFirstName); // where ptFirstName is 'John' in single quotes.
回答by dasblinkenlight
The reason
原因
ptFirstName.Replace("\"", "'");
does not work is that string
is immutable. You need to use
不工作string
是不可变的。你需要使用
ptFirstName = ptFirstName.Replace("\"", "'");
instead. Here is a demo on ideone.
回答by Matt Johnson-Pint
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?
我猜您没有"John"
在文本框中键入内容,但是John
当您设置断点并在 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.
你不会看到引号。
回答by shalongbus
writer.QuoteChar = '\'';
writer.QuoteChar = '\'';
See http://msdn.microsoft.com/en-ca/library/system.xml.xmltextwriter.quotechar.aspxfor details.
有关详细信息,请参阅http://msdn.microsoft.com/en-ca/library/system.xml.xmltextwriter.quotechar.aspx。