9

how to replace any charachter with nothing. for example

1 : string inputString = "This Is Stack OverFlow";
2 : string outputString = inputString.Replace(' ', '');

expected output = "ThisIsStackOverFlow";

I tried line 2 but it says empty Character String in Replace methods second argument. Can any body tell me whats wrong with my Replace Method and why it does not take blank like we normally use in string (for ex : "")?

3
  • possible duplicate of Remove characters from C# string Commented Nov 10, 2014 at 13:19
  • Sorry for posting such a easy Question, i should have looked for its overloaded methods and i got the answer, its Replace (string,string) method which can do my work, but still want to know why empty didn't work in second argument of Repalce(char, char) method
    – Ashwin
    Commented Nov 10, 2014 at 13:20
  • As I stated in my answer, '' isn't a valid character. You actually want no character, so you can't use that notation and you need to use the string one. The closest option is a null character, but you don't want that.
    – Andrew
    Commented Nov 10, 2014 at 13:23

2 Answers 2

22

Because you are using the Replace(char, char) overload instead of Replace(string, string) ('' is not a valid character). Just use this:

string ouputString = inputString.Replace(" ", "");
-1

You can simply use the '\0' character

Console.WriteLine("String w i t h. Holes !".Replace(' ','\0'));
2
  • Already mentioned in comments 9 years ago. If you're going to turn it into a full answer, you should at least mention the consequences of embedding NUL characters into the middle of a string in .NET
    – Ben Voigt
    Commented Nov 6, 2023 at 17:28
  • It is not explicitly stating about how to write the no character char so it may be helpful to somebody. I don't know if it is any different in .NET but in some languages \0 is delimiting end of strings. But the above code works fine so far with C# and it solves the problem asked here. Hence the full answer. If you want to elaborate on the consequences of NUL character please go ahead. Cheers Commented Dec 2, 2023 at 18:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.