How to Remove All Whitespace From a String in C#

You might come across situations where you need to remove all whitespace characters from a string. Whitespace characters include spaces, tabs, newlines, and carriage returns. In this article, we will discuss remove all whitespace characters from a string in C#.

Install Required Software

  • NET Core SDK from here
  • Visual Studio or Visual Studio Code from here

String.Replace() method

The String.Replace() method is the simplest approach to removing whitespace characters from a string. This method replaces all occurrences of one string or character in the current string object with another string or character. This method can be used to replace all whitespace characters with an empty string. Here’s an example:

    public static string removewhitespaceReplace(string strvalue)
        {
            string stringvalue = strvalue.Replace(" ", "")
                                         .Replace("\n", "")
                                         .Replace("\t", "")
                                         .Replace("\r", "");
            return stringvalue;
        }

Using LINQ

LINQ provides a functional way to manipulate collections in C#. We can use LINQ to remove all whitespace characters from a string. Here’s an example:

   public static string removewhitespaceLinq(string strvalue)
        {
            string stringvalue = new string(strvalue.Where(w => !Char.IsWhiteSpace(w)).ToArray());
            return stringvalue;
        }

We use the Where() extension function to remove whitespace characters from the input string. The ToArray() method creates a character array from the filtered characters, and the new string() constructor creates a new string from the character array.

Using Regular Expressions

Regular expressions can be used to remove all whitespace characters from a string. For example, the following code uses a regular expression to remove all whitespace characters from the string.

  public static string removewhitespaceRegularExp(string strvalue)
        {
            string stringvalue = Regex.Replace(strvalue, @"\s+", "");
            return stringvalue;
        }

The regular expression @”\s+” matches any sequence of one or more whitespace characters. The Replace() method replaces all matches of this regular expression with an empty string.

Using StringBuilder

StringBuilder is a mutable string class in C#. We can use StringBuilder to remove all whitespace characters from a string. Here’s an example:

  public static string removewhitespaceStringBuilder(string strvalue)
        {
            string stringvalue;
            StringBuilder sb = new StringBuilder();
            foreach(char c in strvalue)
            {   if (!Char.IsWhiteSpace(c))
                sb.Append(c);
            }            
            return stringvalue=sb.ToString();
        }

In the above code, we loop through each character in the input string and append non-whitespace characters to the StringBuilder.

Full Source Code

  static void Main(string[] args)
        {
            string inputstring = "\n Hello \t   World  \r    ";

            string outputstring = removewhitespaceStringBuilder(inputstring);
            Console.WriteLine("Result " + outputstring);
        }
 public static string removewhitespaceReplace(string strvalue)
        {

            string stringvalue = strvalue.Replace(" ", "")
                                         .Replace("\n", "")
                                         .Replace("\t", "")
                                         .Replace("\r", "");
            return stringvalue;
        }
        public static string removewhitespaceLinq(string strvalue)
        {
            string stringvalue = new string(strvalue.Where(w => !Char.IsWhiteSpace(w)).ToArray());
            return stringvalue;
        }

        public static string removewhitespaceRegularExp(string strvalue)
        {
            string stringvalue = Regex.Replace(strvalue, @"\s+", "");
            return stringvalue;
        }

        public static string removewhitespaceStringBuilder(string strvalue)
        {
            string stringvalue;
            StringBuilder sb = new StringBuilder();
            foreach(char c in strvalue)
            {   if (!Char.IsWhiteSpace(c))
                sb.Append(c);
            }            
            return stringvalue=sb.ToString();
        }
    }
}

Which Method Should I Use?

The best method for removing all whitespace characters from a string is determined by the needs of your application.

More Post: Base64 Encoding and Decoding in C#

Conclusion
In this article, we have discussed different ways to remove all whitespace characters from a string in C#. We have seen that the StringReplace method, RegexReplace method, Linq method, and StringBuilder method are some of the ways to achieve this.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments