Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string in GO by array of runes?

Tags:

string

split

go

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"}
like image 974
Lobster Avatar asked Mar 03 '14 19:03

Lobster


People also ask

How do you split a string in go?

The Split() method​ in Golang (defined in the strings library) breaks a string down into a list of substrings using a specified separator. The method returns the substrings in the form of a slice.

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I convert a string to an array in Golang?

To convert a string into array of characters (which is slice of runes) in Go language, pass the string as argument to []rune(). This will create a slice of runes where each character is stored as an element in the resulting slice.

How do you convert a string to a slice?

strings.Split() function. The Split function takes a string and a delimiter as parameters and returns a slice of strings where each substring was formally separated by the given delimiter.


1 Answers

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"]
like image 78
peterSO Avatar answered Sep 25 '22 20:09

peterSO