Tag Archives: stringbuilder

Removing Character from String in C Sharp

I need to process a string in order to remove certain unwanted characters. One such character has an ASCII value of Hex 01. I happen to be using a StringBuilder, which offers a Replace method similar to String.Replace.

I can’t simply do a Replace(Convert.ToString(0x1), "") which just removes all instances of the string “1”. To get the correct character, I can use Convert.ToChar(0x1) or simply ‘\x01’. However, I can’t remove a character with the Replace(char, char) overload because there is no such thing as an “empty” character literal that’s analogous to an empty string. Each value of char type is mapped to a code point and is therefore exactly one character long.

To remove the character, simply take an additional step and convert it to a string: Replace('\x01'.ToString(), "").