简体   繁体   English

替换字符串c#中的控制字符

[英]Replace control character in string c#

Some text fields in my database have bad control characters embedded. 我的数据库中的某些文本字段嵌入了错误的控制字符。 I only noticed this when trying to serialize an object and get an xml error on char  在尝试序列化对象并在char 上获取xml错误时,我才注意到这一点 and   . There are probably others. 可能还有其他人。

How do I replace them using C#? 如何使用C#替换它们? I thought something like this would work: 我认为这样的事情会起作用:

text.Replace('\x2', ' ');

but it doesn't. 但事实并非如此。 Any help appreciated. 任何帮助赞赏。

字符串是不可变的 - 您需要重新分配:

text = text.Replace('\x2', ' ');

exactly as was said above, strings are immutable in C#. 正如上面所说,字符串在C#中是不可变的。 This means that the statement: 这意味着声明:

text.Replace('\x2', ' '); 

returned the string you wanted,but didn't change the string you gave it. 返回了你想要的字符串,但没有改变你给它的字符串。 Since you didn't assign the return value anywhere, it was lost. 由于您没有在任何地方分配返回值,因此丢失了。 That's why the statement above should fix the problem: 这就是上面的陈述应该解决问题的原因:

text = text.Replace('\x2', ' '); 

If you have a string that you are frequently making changes to, you might look at the StringBuilder object, which works very much like regular strings, but they are mutable, and therefore much more efficient in some situatations. 如果你有一个经常对其进行更改的字符串,你可能会看一下StringBuilder对象,它与常规字符串非常相似,但它们是可变的,因此在某些情况下效率更高。

Good luck! 祝好运!

-Craig -Craig

The larger problem you're dealing with is the XmlSerialization round trip problem. 您正在处理的更大问题是XmlSerialization往返问题。 You start with a string, you serialize it to xml, and then you deserialize the xml to a string. 您以字符串开头,将其序列化为xml,然后将xml反序列化为字符串。 One expects that this always results in a string that is equivalent to the first string, but if the string contains control characters, the deserialization throws an exception. 我希望这总是会产生一个等同于第一个字符串的字符串,但如果字符串包含控制字符,则反序列化会引发异常。

You can fix that by passing an XmlTextReader instead of a StreamReader to the Deserialize method. 您可以通过将XmlTextReader而不是StreamReader传递给Deserialize方法来解决此问题。 Set the XmlTextReader's Normalization property to false . 将XmlTextReader的Normalization属性设置为false

You should also be able to solve this problem by serializing the string as CDATA; 您还应该能够通过将字符串序列化为CDATA来解决此问题; see How do you serialize a string as CDATA using XmlSerializer? 请参阅如何使用XmlSerializer将字符串序列化为CDATA? for more information. 欲获得更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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