dongzhina7098 2016-05-30 19:07
浏览 20
已采纳

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

Basically I have []int{1, 2, 3}, I want a one-liner that transforms this into the string "1, 2, 3" (I need the delimiter to be custom, sometimes ., sometimes ,, etc). Below is the best I could come up with. Searched online and did not seem to find a better answer.

In most languages there is in-built support for this, e.g.:

python:

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

go:

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, ", "))
}

Surely there must be an utility buried into go that allows me to do this with a one-liner?

I know that there is strings.Join(A, ", "), but that only works if A is already []string.

  • 写回答

4条回答 默认 最新

  • dreamy6301 2016-05-30 20:19
    关注

    To convert
    A := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}

    to a one line delimited string like
    "1,2,3,4,5,6,7,8,9"
    use:

    strings.Trim(strings.Join(strings.Fields(fmt.Sprint(A)), delim), "[]")
    

    or:

    strings.Trim(strings.Join(strings.Split(fmt.Sprint(A), " "), delim), "[]")
    

    or:

    strings.Trim(strings.Replace(fmt.Sprint(A), " ", delim, -1), "[]")
    

    and return it from a function such as in this example:

    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
    }
    

    To include a space after the comma you could call arrayToString(A, ", ") or conversely define the return as return strings.Trim(strings.Replace(fmt.Sprint(a), " ", delim + " ", -1), "[]") to force its insertion after the delimiter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘