I have a string that is comma separated, so it could be
test1, test2, test3
or test1,test2,test3
or test1, test2, test3
.
I split this in Go currently with strings.Split(s, ",")
, but now I have a []string
that can contain elements with an arbitrary numbers of whitespaces.
How can I easily trim them off? What is best practice here?
This is my current code
var property= os.Getenv(env.templateDirectories)
if property != "" {
var dirs = strings.Split(property, ",")
for index,ele := range dirs {
dirs[index] = strings.TrimSpace(ele)
}
return dirs
}
I come from Java and assumed that there is a map/reduce etc functionality in Go also, therefore the question.
To trim spaces around string in Go language, call TrimSpace function of strings package, and pass the string as argument to it. TrimSpace function returns a String.
To split the sentences by comma, use split(). For removing surrounding spaces, use trim().
Split method, which is not to trim white-space characters and to include empty substrings.
You can use strings.TrimSpace
in a loop. If you want to preserve order too, the indexes can be used rather than values as the loop parameters:
Go Playground Example
EDIT: To see the code without the click:
package main
import (
"fmt"
"strings"
)
func main() {
input := "test1, test2, test3"
slc := strings.Split(input , ",")
for i := range slc {
slc[i] = strings.TrimSpace(slc[i])
}
fmt.Println(slc)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With