Removing surrounding whitespace
Text from users, files and copy-and-paste often arrives with extra spaces at the edges. C# calls the fix trimming, and strings have three methods for it:
| Call | What it removes |
|---|---|
s.Trim() | Whitespace at the start and at the end |
s.TrimStart() | Whitespace at the start only |
s.TrimEnd() | Whitespace at the end only |
Other languages call the same operation strip, which is the name in this lesson's title. In C# the methods are named Trim.
string s = " hello ";
Console.WriteLine("[" + s.Trim() + "]"); // [hello]
Console.WriteLine("[" + s.TrimStart() + "]"); // [hello ]
Console.WriteLine("[" + s.TrimEnd() + "]"); // [ hello]
Console.WriteLine("[" + s + "]"); // [ hello ]
The square brackets are only there to make the spaces visible. The last line shows that s itself still has its spaces: strings are immutable, so trimming returns a new string.
What counts as whitespace
Trimming removes more than the space character. Tabs, newlines and carriage returns count too:
string t = "\t hi \n";
Console.WriteLine("[" + t.Trim() + "]"); // [hi]
Only the edges are touched. Spaces between words stay where they are, so "a b".Trim() is still a b. If a string contains nothing but whitespace, Trim() returns an empty string.
Trimming other characters
You can also tell Trim which characters to remove by passing them in:
Console.WriteLine("xxhixx".Trim('x')); // hi
It removes every leading and trailing x, and stops at the first character that is not in the set. Characters in the middle are never removed.
The same idea works one side at a time with TrimStart and TrimEnd:
Console.WriteLine("Wow!!!".TrimEnd('!')); // Wow
Console.WriteLine("007".TrimStart('0')); // 7
Console.WriteLine("..a..b..".Trim('.')); // a..b
In the last line the dots between a and b survive, because trimming stops at the first character that is not in the set.
Why trimming matters
A stray space makes two strings that look alike compare as different:
string typed = " yes ";
Console.WriteLine(typed == "yes"); // False
Console.WriteLine(typed.Trim() == "yes"); // True
Trimming input before you compare or store it avoids that class of bug. It is often combined with other string methods, such as ToLower, because each one returns a string you can call the next method on.
Checking for blank text
Sometimes you only need to know whether a string has anything useful in it. string.IsNullOrWhiteSpace answers that without creating a trimmed copy, and it also copes with null:
Console.WriteLine(string.IsNullOrWhiteSpace(" \t")); // True
Console.WriteLine(string.IsNullOrWhiteSpace(" a")); // False
Trim recognises the same set of whitespace characters, including the non-breaking space that sometimes arrives from web pages and documents.
Trimming before other steps
Trim is usually the first step in cleaning text, because stray whitespace upsets later steps. Raw input can end with a line break, which Trim also removes:
string raw = " Yes \r\n";
Console.WriteLine(raw.Trim().ToLower() == "yes"); // True
It also helps before splitting. Without trimming, " a b c ".Split(' ') returns empty pieces at both ends and in the middle. Trimming first removes the edge pieces, and the RemoveEmptyEntries option of Split handles the doubled space in the middle.
The exercise, step by step
The lesson gives you s set to " hello ", with two spaces on each side.
- Declare a
stringnamedresult.Trimreturns a string. - Assign it
s.Trim(). Both ends lose their spaces, leavinghello.
string s = " hello ";
string result = s.Trim();
Now result is hello and s still has its spaces.
Reading the result
The trimmed string can be shorter, so its Length drops by the number of characters removed. For the lesson's example, s.Length is 9 and result.Length is 5. If the string has nothing to trim, you simply get an equal string back, so it is always safe to call Trim on text that may or may not have extra whitespace.
Common mistakes
- Calling
strip. C# has noStripmethod on strings. The method isTrim, with a capital T. - Expecting
sto change.s.Trim();on its own line discards the result. Store it, either in a new variable or back ins. - Expecting inner spaces to go.
Trimonly works at the edges. To remove all spaces, useReplace(" ", ""). - Trimming a
null. CallingTrim()on anullvariable throws aNullReferenceException.
Key takeaways
Trim()removes whitespace from both ends,TrimStart()from the start andTrimEnd()from the end.- Whitespace includes tabs and newlines, not just spaces.
- Each method returns a new string; the original is unchanged.
- Characters inside the string are never removed.