0
0
CsharpHow-ToBeginner · 3 min read

How to Remove Whitespace from String in C#

To remove all whitespace from a string in C#, use string.Replace(" ", "") to remove spaces or Regex.Replace to remove all whitespace characters. To remove whitespace only at the start or end, use string.Trim().
📐

Syntax

Here are common ways to remove whitespace in C#:

  • string.Replace(" ", ""): Removes all space characters.
  • string.Trim(): Removes whitespace from the start and end of the string.
  • Regex.Replace(input, "\s+", ""): Removes all whitespace characters (spaces, tabs, newlines).
csharp
string result = input.Replace(" ", "");
string trimmed = input.Trim();
string noWhitespace = Regex.Replace(input, "\s+", "");
💻

Example

This example shows how to remove spaces and all whitespace from a string.

csharp
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "  Hello \t World \n ";

        // Remove only spaces
        string noSpaces = input.Replace(" ", "");

        // Remove whitespace from start and end
        string trimmed = input.Trim();

        // Remove all whitespace characters
        string noWhitespace = Regex.Replace(input, "\s+", "");

        Console.WriteLine($"Original: '{input}'");
        Console.WriteLine($"No spaces: '{noSpaces}'");
        Console.WriteLine($"Trimmed: '{trimmed}'");
        Console.WriteLine($"No whitespace: '{noWhitespace}'");
    }
}
Output
Original: ' Hello World ' No spaces: 'Hello World ' Trimmed: 'Hello World' No whitespace: 'HelloWorld'
⚠️

Common Pitfalls

Common mistakes include:

  • Using Replace(" ", "") only removes space characters, but not tabs or newlines.
  • Using Trim() only removes whitespace at the start and end, not inside the string.
  • Not including using System.Text.RegularExpressions; when using Regex.Replace.
csharp
string input = " Hello \t World ";

// Wrong: only removes spaces, tabs remain
string wrong = input.Replace(" ", "");

// Right: removes all whitespace
string right = Regex.Replace(input, "\s+", "");
📊

Quick Reference

MethodDescriptionRemoves
string.Replace(" ", "")Removes all space charactersSpaces only
string.Trim()Removes whitespace at start and endLeading and trailing whitespace
Regex.Replace(input, "\s+", "")Removes all whitespace charactersSpaces, tabs, newlines, all whitespace

Key Takeaways

Use string.Replace(" ", "") to remove only space characters inside a string.
Use string.Trim() to remove whitespace only from the start and end of a string.
Use Regex.Replace(input, "\s+", "") to remove all types of whitespace anywhere in the string.
Remember to include using System.Text.RegularExpressions when using Regex.
Choose the method based on whether you want to remove spaces inside, at edges, or all whitespace.