c sharp

How to Remove Whitespaces in a String in C#

In C#, whitespace characters are represented by the space, tab, newline, carriage return, and other similar characters. Removing whitespaces from a string is a common task in string manipulation, especially when dealing with user inputs, file processing, and data parsing. This article delves into various methods for removing whitespaces from a string in C#.

What are whitespaces?

Whitespaces are characters that represent empty or blank spaces in a text string. They are typically used to separate words and other elements of a text and to improve the readability and visual appearance of the text.

In programming, whitespaces encompass characters such as spaces, tabs, newlines, and carriage returns. In many programming languages, whitespaces are ignored or treated as insignificant when processing or interpreting code, but they can affect the layout, formatting, and syntax of the code.

How to Remove Whitespaces in a String

Removing or manipulating whitespaces is a common task in string processing and text manipulation. Normalizing or standardizing text inputs often involves the need to remove or replace whitespaces. To remove unnecessary characters that can affect the functionality of the code or the accuracy of the data, or to improve the efficiency and readability of the code, here are some for doing it:

1: Using String.Replace() Method

To remove whitespaces from a string in a straightforward manner, the String.Replace() method can be utilized. In this scenario, we can designate the space character ” ” as the old value and an empty string “” as the new value. By doing so, all spaces within the string will be effectively removed.

using System;

class whitepace
{
    static void Main(string[] args)
    {
        string originalString = " Hello, Sam! ";
        string trimmedString = originalString.Replace(" ", "");
        Console.WriteLine(trimmedString);
    }
}

 
This program includes a using statement that imports the System namespace, which is required for using the Console class for console input and output.

Within the Main method, we initialize a string variable named originalString with the value “Hello, Sam!”.

Next, we declare another string variable named trimmedString and assign it the outcome of invoking the Replace() method on originalString. The Replace() method is called with two arguments: the first argument represents the old substring we wish to replace, which in this case is a single space character ” “, and the second argument signifies the new substring we desire to replace it with, namely an empty string “”.

2: Using String.Join() Method

Another way to remove whitespaces from a string is to split the string into an array of substrings using the String.Split() method and then join the substrings back together using the String.Join() method. To eliminate any empty substrings that may arise from consecutive whitespaces, we can utilize the StringSplitOptions.RemoveEmptyEntries option.

using System;

class whitepace
{
    static void Main(string[] args)
    {
        string originalString = " Hello, Sam! ";
        string[] substrings = originalString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        string trimmedString = String.Join("", substrings);
        Console.WriteLine(trimmedString);
    }
}

 
Within this code, there is a declaration of a string variable named “originalString” and it is initialized with the value “Hello, Sam!” and then undergoes splitting into an array of substrings using a space character as the delimiter. The RemoveEmptyEntries option is used to exclude any empty substrings from the resulting array.

Subsequently, the code employs the String.Join() method to merge the non-empty substrings into a unified string, utilizing an empty string as the separator.

Lastly, the code utilizes the Console.WriteLine to display the trimmed string on the console window. Upon executing this code, you can expect to observe the output “Hello,Sam!” being printed on the console.

3: Using Regular Expressions

Regular expressions provide a powerful way to match and replace patterns in strings. By utilizing the Regex.Replace() method, we can effectively eliminate all whitespace characters from a string.

using System;
using System.Text.RegularExpressions;

class whitespace
{
    static void Main(string[] args)
    {
        string originalString = " Hello, Sam! ";
        string trimmedString = Regex.Replace(originalString, @"\s+", "");
        Console.WriteLine(trimmedString); "
    }
}

 
In this code, a string variable named “originalString” is declared and initialized with the value “Hello, Sam!”. The code then employs the Regex.Replace() method to replace one or more whitespace characters (represented by the regular expression \s+) with an empty string.

Finally, the code uses the Console.WriteLine() to output the trimmed string to the console window and When you execute this program, you will observe the output “Hello,Sam!” printed to the console.

In this particular example, the regular expression pattern @”\s+” is employed to match one or more whitespace characters (including spaces, tabs, and newlines) and subsequently replaces them with an empty string.

4: Using LINQ

We can also remove whitespaces from a string using LINQ. We can use the Where() method to filter out whitespace characters and then join the remaining characters back together using the String.Concat() method.

using System;
using System.Linq;

class whitespace
{
    static void Main(string[] args)
    {
        string originalString = " Hello, Sam! ";
        string trimmedString = new string(originalString.Where(c => !char.IsWhiteSpace(c)).ToArray());
        Console.WriteLine(trimmedString);
    }
}

 
In this code snippet, a string variable called “originalString” is declared and initialized with the value ” Hello, Sam! “. It then creates a new string variable named trimmedString using a LINQ expression that filters out any whitespace characters from the original string. The Where() extension method is used to filter the characters and the resulting characters are converted to an array and passed to the new string constructor to create a new string.

Finally, the code uses the Console.WriteLine() to output the trimmed string to the console window. Upon executing this code, you can expect to observe the output “Hello, Sam!” displayed on the console.

Conclusion

In C#, there exist various methods for removing whitespaces from a string and those are String.Replace() method, String.Join() method, using regular expressions and using LINQ. It is crucial to opt for a method that is efficient, robust, and easily comprehensible, allowing for ease of maintenance and readability.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.