Which is the effective way to trim the leading and trailing white spaces of string variable in Go?
Just as @Kabeer has mentioned, you can use TrimSpace and here is an example from golang documentation:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
Output: Hello, Gophers
And simply follow this link - https://golang.org/pkg/strings/#TrimSpace
A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.
(example: the string value of {"first_name":" I have whitespace "}
will convert to "\" I have whitespace \""
)
Before you can trim anything, you'll need to remove the extra quotes first:
playground example
// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string
// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
ns := string(data)
// Make sure we don't have a blank string of "\"\"".
if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
*s = ""
return nil
}
// Remove the added wrapping quotes.
ns, err := strconv.Unquote(ns)
if err != nil {
return err
}
// We can now trim the whitespace.
*s = ScrubString(strings.TrimSpace(ns))
return nil
}
There's a bunch of functions to trim strings in go.
See them there : Trim
Here's an example, adapted from the documentation, removing leading and trailing white spaces :
fmt.Printf("[%q]", strings.Trim(" Achtung ", " "))
For trimming your string, Go's "strings" package have TrimSpace()
, Trim()
function that trims leading and trailing spaces.
Check the documentation for more information.
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"