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


Removing leading and trailing spaces from a string eliminates all whitespace before the first character and after the last character in the string. For example, removing leading and trailing spaces from " abc def " results in "abc def". The strings.TrimSpace() method from the standard library, trim the white spaces from both ends of a string.

Example

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "\t Hello, World\n "
    fmt.Printf("Before Trim Length: %d String:%v\n", len(str), str)
    trim := strings.TrimSpace(str)
    fmt.Printf("After Trim Length: %d String:%v\n", len(trim), trim)
}
Most Helpful This Week