HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howandtrimleadingtrailingwhitespacesstring

Problem

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

Solution

strings.TrimSpace(s)

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"

Code Snippets

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)
}
16 "\t Hello, World\n "
12 "Hello, World"

Context

Stack Overflow Q#22688010, score: 385

Revisions (0)

No revisions yet.