一尘不染

一线将[] int转换为字符串

go

基本上[]int{1, 2, 3},我有一个单线将其转换为字符串“
1、2、3”(我需要定界符是自定义的,有时是.,有时,是等)。以下是我能想到的最好的方法。在线搜索,似乎找不到更好的答案。

在大多数语言中,对此都有内置的支持,例如:

蟒蛇:

> A = [1, 2, 3]
> ", ".join([str(a) for a in A])
'1, 2, 3'

走:

package main

import (
    "bytes"
    "fmt"
    "strconv"
)

// Could not find a one-liner that does this :(.
func arrayToString(A []int, delim string) string {

    var buffer bytes.Buffer
    for i := 0; i < len(A); i++ {
        buffer.WriteString(strconv.Itoa(A[i]))
        if i != len(A)-1 {
            buffer.WriteString(delim)
        }
    }

    return buffer.String()
}

func main() {
    A := []int{1, 2, 3}
    fmt.Println(arrayToString(A, ", "))
}

当然,肯定有一个实用工具可以让我用单线执行此操作吗?

我知道有strings.Join(A, ", "),但是仅当A已经[]字符串时才有效。


阅读 189

收藏
2020-07-02

共1个答案

一尘不染

转换
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 main

import "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 return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim + " ", -1), "[]")以强制将其插入定界符之后。

2020-07-02