Remove whitespace from a string
Remove spaces, tabs, line breaks, and other whitespace characters from a string.
Course progress
Problem 25 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = " C#\t is\n fun "
Expected output
C#isfun
What is happening?
Remove the leading, trailing, space, tab, and newline characters while preserving every non-whitespace character.
Solution strategy
Build the right mental model
Append only non-whitespace characters to a StringBuilder so the result is built efficiently in one pass.
Core concepts
strings · StringBuilder
Complexity
Time O(n), space O(n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for remove-whitespace
using System;
using System.Text;
class Program
{
static string RemoveWhitespace(string text)
{
var result = new StringBuilder();
foreach (char symbol in text)
if (!char.IsWhiteSpace(symbol)) result.Append(symbol);
return result.ToString();
}
static void Main()
{
Console.WriteLine(RemoveWhitespace(" C#\t is\n fun "));
}
}Knowledge check
Questions students often ask
What is the main idea behind remove whitespace from a string?
Append only non-whitespace characters to a StringBuilder so the result is built efficiently in one pass.
What is the time and space complexity of this solution?
Time O(n), space O(n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.