Remove whitespace in elements in string C#

I suppose you need the string with whitespaces removed. You could use String.Replace()

RESULT = RESULT.Replace(" ",string.Empty);

Alternatively, you could also use Regex for replace,

RESULT = Regex.Replace(RESULT,@"\s",string.Empty);

The regex approach would ensure replacement of all whitespace characters including tab,space etc


See the answer by Pavel Anikhouski, which checks the performance of all suggested solutions and actually shows that the simplified LINQ solution does not help performance too much - good to know :-) .

Simpler solution with LINQ:

string.Join(string.Empty, input.Where(c=>!char.IsWhiteSpace(c)));

First we filter away all whitespace characters and then we join them into a string. This has only one string allocation (to create the resulting string) and handles all kinds of whitespace characters, not only spaces.

Original answer

Use a StringBuilder to build up the resulting string and then go through the input string with a foreach, always checking char.IsWhiteSpace(character). In case the character is not whitespace, append it in the StringBuilder by calling Append(character) method. At the end just return the resulting string by calling ToString() on the StringBuilder.

var builder = new StringBuilder();
foreach(var character in input)
{
   if (!char.IsWhiteSpace(character))
   {
      builder.Append(character);
   }
}
return builder.ToString();

This implementation is more efficient, as it does not produce any string allocations, except for the end result. It just works with the input string and reads it once.


Isn't what you looking for?

var noWhiteSpaces = RESULT.Replace(" ", string.Empty);

Tags:

C#

Split