转换
A := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
到一行分隔字符串,例如
“ 1,2,3,4,5,6,7,8,9”,请
使用:
strings.Trim(strings.Join(strings.Fields(fmt.Sprint(A)), delim), "[]")
要么:
strings.Trim(strings.Join(strings.Split(fmt.Sprint(A), " "), delim), "[]")
要么:
strings.Trim(strings.Replace(fmt.Sprint(A), " ", delim, -1), "[]")
并从此示例中的函数返回它:
package mainimport "fmt"import "strings"func arrayToString(a []int, delim string) string { return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim, -1), "[]") //return strings.Trim(strings.Join(strings.Split(fmt.Sprint(a), " "), delim), "[]") //return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(a)), delim), "[]")}func main() { A := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println(arrayToString(A, ",")) //1,2,3,4,5,6,7,8,9}
要在逗号后包含空格,您可以调用
arrayToString(A, ", ")或反过来定义return
returnstrings.Trim(strings.Replace(fmt.Sprint(a), " ", delim + " ", -1),"[]")以强制将其插入定界符之后。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)