How to split string in GO by array of runes?

Issue

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"}

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"]

Answered By – peterSO

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.