英文:
How to recursively join a string to an array of type string in golang
问题
我已经为您翻译了您的内容:
我已经为相当长一段时间在这个问题上苦苦挣扎。我基本上想创建一个递归函数,将一个字符串与一个数组连接起来。
像这样:
join(", ", ["one","two","three"])
应该看起来像这样 "one, two, three"
英文:
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
得分: 3
在strings
模块中已经有一个名为Join
的函数。但它不是递归的,如果你需要递归的话,可以像这样实现:
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"}))
}
希望对你有帮助!
英文:
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"}))
}
答案2
得分: 2
这是一个类似的示例代码:
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"}))
}
这个函数只支持一级展开,但你可以根据你的需求在 switch 语句中自定义递归。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论