How to replace a char in string with an Empty character in C#.NET

val.Replace("-", "");

MSDN Source


You can use a different overload of Replace() that takes string.

val = val.Replace("-", string.Empty)

Since the other answers here, even though correct, do not explicitly address your initial doubts, I'll do it.

If you call string.Replace(char oldChar, char newChar) it will replace the occurrences of a character with another character. It is a one-for-one replacement. Because of this the length of the resulting string will be the same.

What you want is to remove the dashes, which, obviously, is not the same thing as replacing them with another character. You cannot replace it by "no character" because 1 character is always 1 character. That's why you need to use the overload that takes strings: strings can have different lengths. If you replace a string of length 1, with a string of length 0, the effect is that the dashes are gone, replaced by "nothing".


This seems too simple, but:

val.Replace("-","");

Tags:

C#