Start learning free

LESSON 65 OF 338 · STRINGS I

String Strip in Go: strings.TrimSpace and Trim

Lesson Read the full explanation

In Go, you can remove leading and trailing whitespace using strings.TrimSpace():

// strings.TrimSpace() removes leading and trailing spaces
s := "  hello  "
result := strings.TrimSpace(s)
// result == "hello"

Here is how a trim function works internally:

func trimSpace(s string) string {
    start, end := 0, len(s)-1
    for start <= end && s[start] == ' ' {
        start++
    }
    for end >= start && s[end] == ' ' {
        end--
    }
    return s[start : end+1]
}

Assignment
Follow the Coding Tutorial and use strings.TrimSpace() to strip whitespace from s!


Hint
Use strings.TrimSpace(s) and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    GO · STRINGS I

    String Strip in Go, explained

    Removing whitespace at the ends

    Text from users, files and forms often has stray spaces or newlines at the start and the end. Go's strings.TrimSpace(s) returns a copy of s without the leading and trailing whitespace. The name comes from "trim" rather than "strip", but it does the same job as the strip functions of other languages.

    s := "  hello  "
    result := strings.TrimSpace(s)
    fmt.Printf("%q\n", result) // "hello"
    

    The %q verb prints a string in quotes, which makes any remaining spaces visible. Plain Println would hide them. Strings in Go are immutable, so TrimSpace leaves s as it was and returns a new string. If you don't keep the return value, nothing is trimmed.

    Exercise step by step

    1. Start from the given variable. s holds " hello ", with two spaces on each side.
    2. Declare result with :=. It will hold the trimmed string.
    3. Call strings.TrimSpace(s) and assign its return value to result.

    The solution in Go

    s := "  hello  "
    
    result := strings.TrimSpace(s)
    

    Afterwards, result is "hello" and s is unchanged.

    What counts as whitespace

    TrimSpace removes spaces, tabs, newlines, carriage returns and the other characters Unicode treats as whitespace. It only touches the two ends. Spaces inside the text stay where they are, so strings.TrimSpace(" a b ") is "a b" with both inner spaces.

    How trimming works

    You can write the idea yourself with two indexes, one moving in from each end, and then slice what is left. This version handles only the space character, to keep the logic visible:

    func trimSpace(s string) string {
        start, end := 0, len(s)-1
        for start <= end && s[start] == ' ' {
            start++
        }
        for end >= start && s[end] == ' ' {
            end--
        }
        return s[start : end+1]
    }
    

    The first loop moves start forward past leading spaces. The second moves end backward past trailing ones, and it stops at start so the two never cross. The slice s[start : end+1] then keeps everything between them. The +1 is needed because the end of a slice is excluded. For a string of only spaces, start ends at len(s) and the slice is empty, which is a valid result. The comparisons against ' ' use a rune literal, since s[start] is a byte. This helper leaves a tab or a newline in place, where strings.TrimSpace removes it: strings.TrimSpace("\thi\n") is "hi".

    Trimming other characters

    Several related functions cover cases where whitespace is not what you want to remove:

    • strings.Trim(s, cutset) removes any of the characters in cutset from both ends: strings.Trim("***hi***", "*") is "hi".
    • strings.TrimLeft and strings.TrimRight work on one side only, so strings.TrimLeft(" hi ", " ") is "hi ".
    • strings.TrimPrefix(s, p) and strings.TrimSuffix(s, p) remove one exact prefix or suffix, once.

    The second argument of Trim, TrimLeft and TrimRight is a set of characters, not a word to remove. strings.Trim("abcba", "ab") returns "c", because every leading and trailing a and b is removed. To remove a whole word once, use TrimPrefix or TrimSuffix.

    Common mistakes

    • Ignoring the return value. strings.TrimSpace(s) on its own line compiles, but s keeps its spaces.
    • Expecting inner spaces to go. Trimming works only at the ends. Use strings.Fields or strings.ReplaceAll for the middle.
    • Calling it as a method. s.TrimSpace() doesn't exist in Go.
    • Trimming a cutset by mistake. Passing a word to Trim removes letters, not the word.

    Where trimming is useful

    Trimming is the usual first step when you clean up input before using it. A name typed as " Ada " should match "Ada", and a line read from a file often ends with a newline you don't want to keep. Trim first, then compare, split or convert. Trimming twice does no harm: a string with no whitespace at its ends comes back as it was, and an empty string stays empty.

    It also helps to know what trimming does not do. It does not shorten the text to fit a length, and it does not collapse a run of spaces in the middle into one. Those are different jobs with different functions.

    Key takeaways

    • strings.TrimSpace(s) returns a copy without leading and trailing whitespace.
    • The original string never changes, so store the result.
    • strings.Trim and its relatives remove chosen characters, prefixes or suffixes.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free