Search code examples
c#whitespace

How to trim whitespace between characters


How to remove whitespaces between characters in c#?

Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".

But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?


Solution

  • You could use String.Replace method

    string str = "C Sharp";
    str = str.Replace(" ", "");
    

    or if you want to remove all whitespace characters (space, tabs, line breaks...)

    string str = "C Sharp";
    str = Regex.Replace(str, @"\s", "");