C# – Remove spaces from a string

The simplest way to remove spaces from a string is by using string.Replace(). Here’s an example:

string input = " a b   c ";

string cleanedInput = input.Replace(" ", string.Empty);

Console.WriteLine($"Before: [{input}]");
Console.WriteLine($"After: [{cleanedInput}]");
Code language: C# (cs)

This outputs the following. Notice the spaces are removed.

Before: [ a b   c ]
After: [abc]Code language: plaintext (plaintext)

string.Replace() is good for removing all occurrences of a specific character (” ” in this case). When you want to remove all whitespace characters (spaces, tabs, newlines, etc..), there are better options, as I’ll show below.

Remove whitespace characters from start or end of a string

To remove all whitespace characters from the start or end of a string, use one of these trim methods:

  • string.TrimStart(): Removes whitespace characters from the start of the string.
  • string.TrimEnd(): Removes whitespace characters from the end of the string.
  • string.Trim(): Removes whitespace characters from the start AND end of the string.

All of these return a new string with the whitespaces trimmed off. Here’s an example of trimming off whitespaces from the end of a string with string.TrimEnd():

string input = "hello world \t \n";

string cleanedInput = input.TrimEnd();

Console.WriteLine($"Before: [{input}]");
Console.WriteLine($"After: [{cleanedInput}]");
Code language: C# (cs)

This outputs the following. Notice it trimmed all whitespace characters (single space, tab, newline) from the end.

Before: [hello world
]
After: [hello world]Code language: plaintext (plaintext)

Remove ALL whitespace characters from a string

When you want to remove all whitespace characters (spaces, tabs, newlines, and more), there are two good options:

  1. Use Regex.Replace() with the \s+ pattern.
  2. Use StringBuilder and char.IsWhiteSpace(). This is about 4x faster than Regex.Replace().

These two options are the right tools for the job. They handle whitespace characters as a category, as opposed to dealing with one type of character at a time (which is what you’d do with chained string.Replace() calls). I’ll show examples below.

Option 1 – Regex.Replace()

Use Regex.Replace() with the “\s+” pattern to replace all whitespace characters with an empty string. Here’s an example:

using System.Text.RegularExpressions;

var input = "\thello \n \tworld \n";

var cleanedInput = Regex.Replace(input, pattern: @"\s+", replacement: string.Empty);

Console.WriteLine($"Before: [{input}]");
Console.WriteLine($"After: [{cleanedInput}]");
Code language: C# (cs)

Note: Use \s+ instead of \s. The + means it matches/replaces multiple consecutive whitespaces at once, which makes it more efficient (about 25% faster).

This outputs the following:

Before: [       hello
        world
]
After: [helloworld]Code language: plaintext (plaintext)

This is slower than the StringBuilder option, but its simplicity is appealing.

Option 2 – Use StringBuilder + char.IsWhiteSpace()

Loop through the string, check each character with char.IsWhiteSpace(), and only add non-whitespace characters to a StringBuilder. Here’s an example:

using System.Text;

var input = "\thello \r\n \tworld \n";

var sb = new StringBuilder(input.Length); //init capacity to eliminate the need to grow the internal char[]

foreach(char c in input)
{
    if (!char.IsWhiteSpace(c))
        sb.Append(c);
}

var cleanedInput = sb.ToString();

Console.WriteLine($"Before: [{input}]");
Console.WriteLine($"After: [{cleanedInput}]");
Code language: C# (cs)

Note: char.IsWhiteSpace() returns true for ALL Unicode characters categorized as whitespace.

This outputs the following:

Before: [       hello
        world
]
After: [helloworld]Code language: plaintext (plaintext)

Leave a Comment