Start learning free

LESSON 63 OF 347 · STRINGS I

String Strip in C#: Trim, TrimStart and TrimEnd

Lesson Read the full explanation

In Java, you can remove leading and trailing whitespace from a string using strip() (Java 11+) or trim():

s.Trim()         // removes leading and trailing whitespace
s.TrimStart()    // removes only leading whitespace
s.TrimEnd()      // removes only trailing whitespace

Here are some examples:

string s = "  hello  ";
Console.WriteLine(s.Trim());       // "hello"
Console.WriteLine(s.TrimStart());  // "hello  "
Console.WriteLine(s.TrimEnd());    // "  hello"

These methods return a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and strip whitespace from s!


Hint
Use s.strip() and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    C# · STRINGS I

    String Strip in C#, explained

    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:

    CallWhat 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.

    1. Declare a string named result. Trim returns a string.
    2. Assign it s.Trim(). Both ends lose their spaces, leaving hello.
            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 no Strip method on strings. The method is Trim, with a capital T.
    • Expecting s to change. s.Trim(); on its own line discards the result. Store it, either in a new variable or back in s.
    • Expecting inner spaces to go. Trim only works at the edges. To remove all spaces, use Replace(" ", "").
    • Trimming a null. Calling Trim() on a null variable throws a NullReferenceException.

    Key takeaways

    • Trim() removes whitespace from both ends, TrimStart() from the start and TrimEnd() 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.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free