This post will discuss how to remove all whitespace from a string in C#.

There are several ways to remove whitespace from a string in C#, which consists of the space character, the horizontal tab \t, the carriage return \r, line feed \n, etc.

1. Using Regex

The regular-expression pattern for whitespace characters is \s. Using this pattern in a regex, we can either replace consecutive whitespace with a single space or remove all whitespace from the input string.

The following code example demonstrates how to remove all whitespace from the input string.

Download  Run Code

 
it is recommended to pre-compile the regular expression to use it more than once.

Download  Run Code

 
To replace consecutive whitespaces with a single space in the input string, we can pass a single space string:

Download  Run Code

2. Using LINQ

We can use LINQ’s Where() method to filter non-whitespace characters from a string using Char.IsWhiteSpace and collect it with the help of the String.Concat() method.

Download  Run Code

That’s all about removing all whitespace from a string in C#.