Which is the effective way to trim the leading and trailing white spaces of string variable in Go?
This question is related to
go
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
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.
@peterSO has correct answer. I am adding more examples here:
package main
import (
"fmt"
strings "strings"
)
func main() {
test := "\t pdftk 2.0.2 \n"
result := strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\n\r pdftk 2.0.2 \n\r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
test = "\r pdftk 2.0.2 \r"
result = strings.TrimSpace(test)
fmt.Printf("Length of %q is %d\n", test, len(test))
fmt.Printf("Length of %q is %d\n\n", result, len(result))
}
You can find this in Go lang playground too.
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:
// 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
}
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"))
}
Source: Stackoverflow.com