user3841999
user3841999

Reputation:

How to recursively join a string to an array of type string in golang

I am struggling with this for quite some time. I basically want to create a function that recursively join a string to an array.

Like this :

join ", " ["one","two","three"] should look like this "one, two, three"

Upvotes: 0

Views: 922

Answers (2)

0xAX
0xAX

Reputation: 21817

There is already Join function in strings module. But it's not recursive, if you need recursive you can make it like this:

package main

import "fmt"

func join_helper(splitter string, arrOfStrings []string, res string) string {
    if len(arrOfStrings) == 0 {
       return res
    }

    if len(arrOfStrings) == 1 {
       return join_helper(splitter, arrOfStrings[1:], res + arrOfStrings[0])
    }

    return join_helper(splitter, arrOfStrings[1:], res + arrOfStrings[0] + splitter)
}

func join(splitter string, arrOfStrings []string) string {
    return join_helper(splitter, arrOfStrings, "")
}

func main(){
    fmt.Println(join(",", []string{"a", "b", "c", "d"}))
}

Upvotes: 3

fabmilo
fabmilo

Reputation: 48330

Something like this

package main

import (
    "fmt"
    "strings"
)

func flatJoin(sep string, args ...interface{}) string {
    values := make([]string, 0)
    for _, item := range args {
        switch v := item.(type) {
        case string:
            values = append(values, v)

        case []string:
            values = append(values, v...)
        case fmt.Stringer:
            values = append(values, v.String())
        default:
            values = append(values, fmt.Sprintf("%v", v))
        }
    }

    return strings.Join(values, sep)

}

func main() {
    fmt.Println(flatJoin(", ", "basic", "other", []string{"here", "more", "inner"}))
}

http://play.golang.org/p/yY6YnZZAak

This supports only one level of flattening, but you can customize the recursion on your switch statement depending on what you are expecting.

Upvotes: 2

Related Questions