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\n", strings.Split("a,,b,c", ","))
https://play.golang.org/p/keaSjjSxgn
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\n", 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\n", delete_empty(arr));
}
Updated Golang Playground.
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