Question

If there is any way to split string into array of strings, when you have as a separator an array of runes? There is an example what I want:

seperators = {' ',')','('}
SomeFunction("my string(qq bb)zz",seperators) => {"my","string","qq","bb","zz"}
Was it helpful?

Solution

For example,

package main

import (
    "fmt"
    "strings"
)

func split(s string, separators []rune) []string {
    f := func(r rune) bool {
        for _, s := range separators {
            if r == s {
                return true
            }
        }
        return false
    }
    return strings.FieldsFunc(s, f)

}

func main() {
    separators := []rune{' ', ')', '('}
    s := "my string(qq bb)zz"
    ss := split(s, separators)
    fmt.Printf("%q\n", s)
    fmt.Printf("%q\n", ss)
}

Output:

"my string(qq bb)zz"
["my" "string" "qq" "bb" "zz"]

OTHER TIPS

with regexp:

package main

import (
    "fmt"
    "regexp"
)

var re = regexp.MustCompile("[() ]")

func main() {
    text := "my string(qq bb)zz"
    splinedText := re.Split(text, -1)
    fmt.Printf("%q\n", text)
    fmt.Printf("%q\n", splinedText)
}

output:

"my string(qq bb)zz"
["my" "string" "qq" "bb" "zz"]

I believe that a simpler approach would be to use the function FieldsFunc. Here is an example of it's implementation:

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func main() {
    f := func(c rune) bool {
        return !unicode.IsLetter(c) && !unicode.IsNumber(c)
    }
    fmt.Printf("Fields are: %q", strings.FieldsFunc("  foo1;bar2,baz3...", f))
}

Output :

Fields are: ["foo1" "bar2" "baz3"]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top