How to trim leading and trailing white spaces of a string?

go
Alex Mathew picture Alex Mathew · Mar 27, 2014 · Viewed 137k times · Source

Which is the effective way to trim the leading and trailing white spaces of string variable in Go?

Answer

peterSO picture peterSO · Mar 27, 2014

For example,

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "\t Hello, World\n "
    fmt.Printf("%d %q\n", len(s), s)
    t := strings.TrimSpace(s)
    fmt.Printf("%d %q\n", len(t), t)
}

Output:

16 "\t Hello, World\n "
12 "Hello, World"