Start learning free

LESSON 66 OF 671 · STRINGS I

String Strip / Trim in Go

Lesson

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

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

Here is how a simple trim function for spaces could work:

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