Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can `strings.split` ignore empty tokens?

Tags:

go

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

like image 277
daplho Avatar asked Oct 17 '17 19:10

daplho


2 Answers

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

like image 186
T. Claverie Avatar answered Oct 19 '22 19:10

T. Claverie


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.

like image 2
Fenton Avatar answered Oct 19 '22 19:10

Fenton