Can you please demonstrate an efficient way to use strings.split
such that empty tokens are not included in the returned slice?
Specifically, the following code returns ["a" "" "b" "c"]
where I want to have it return ["a" "b" "c"]
:
fmt.Printf("%q
", strings.Split("a,,b,c", ","))
Short answer: strings.Split
can't do that.
However, there are more functions to split strings in Go. Notably, you can do what you want with strings.FieldsFunc
. The example here:
splitFn := func(c rune) bool {
return c == ','
}
fmt.Printf("Fields are: %q
", strings.FieldsFunc("a,,b,c", splitFn))
In the playground: https://play.golang.org/p/Lp1LsoIxAK
You can filter out empty elements from an array, so you could do this as a second step.
package main
import (
"fmt"
"strings"
)
func delete_empty (s []string) []string {
var r []string
for _, str := range s {
if str != "" {
r = append(r, str)
}
}
return r
}
func main() {
var arr = strings.Split("a,,b,c", ",");
fmt.Printf("%q
", delete_empty(arr));
}
Updated Golang Playground.
If using regexp
is acceptable, you could split on 1+ separators:
package main
import (
"fmt"
"regexp"
)
func main() {
fmt.Printf("%q
", regexp.MustCompile(",+").Split("a,,b,c", -1))
}