Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace control character in string c#

Tags:

string

c#

hex

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  and . There are probably others.

How do I replace them using C#? I thought something like this would work:

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

but it doesn't. Any help appreciated.

like image 815
Graeme Avatar asked Jul 27 '26 03:07

Graeme


2 Answers

Strings are immutable - you need to reassign:

text = text.Replace('\x2', ' ');
like image 188
BrokenGlass Avatar answered Jul 29 '26 15:07

BrokenGlass


exactly as was said above, strings are immutable in 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.

Good luck!

-Craig

like image 22
Kreg Avatar answered Jul 29 '26 17:07

Kreg