0

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"

1
  • 2
    you mean like strings.Join? Commented Jul 15, 2014 at 17:39

2 Answers 2

3

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"}))
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.