Remove All Whitespace in C#

Published on 11 November 2024 (Updated: 13 May 2026)

Welcome to the Remove All Whitespace in C# page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

if (args is not [var input] || string.IsNullOrEmpty(input))
    return ExitWithError();

RemoveWhitespace(input.AsSpan());
return 0;

static void RemoveWhitespace(ReadOnlySpan<char> input)
{
    char[] buffer = new char[input.Length];
    int j = 0;

    foreach (char c in input)
    {
        if (!char.IsWhiteSpace(c))
            buffer[j++] = c;
    }

    Console.WriteLine(new string(buffer, 0, j));
}

static int ExitWithError()
{
    Console.WriteLine("Usage: please provide a string");
    return 1;
}

Remove All Whitespace in C# was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.