dongmufen8105 2016-12-13 07:18
浏览 1955

在Golang中将字符串转换为数组

I have a string that is from an text file. I was able to get it via 'io/ioutil' it contains the following text:

"[[0, 1], [0, 2], [0,3 ]]"

How do I convert this string to an array that I can use in a for loop?

  • 写回答

1条回答 默认 最新

  • dougong2005 2016-12-14 04:44
    关注

    Go is a strictly typed language so there isn't something like an eval statement that turns data into code directly. In this case that you asked about, seeing that your list of lists is in a format compatible with the JSON format, I thought of using the JSON package to do the parsing. So it takes only three lines of code, defining the type of data that is expected, creating the decoder from the string, and applying the decoder to the data type. The fact that Go is strictly typed but supports reflection (which you won't see in this code) is what took me a little time to get used to. Reflection is what makes the third line possible and why the first line defines the variable as a list of lists ([][]int).

    package main
    
    import (
        "encoding/json"
        "fmt"
        "strings"
    )
    
    // Prints:
    // <nil> [[0 1] [0 2] [0 3]]
    // 0 0 0
    // 0 1 1
    // 1 0 0
    // 1 1 2
    // 2 0 0
    // 2 1 3
    
    func main() {
        jsonstring := "[[0, 1], [0, 2], [0,3 ]]"
        var listoflists [][]int
        dec := json.NewDecoder(strings.NewReader(jsonstring))
        err := dec.Decode(&listoflists)
        fmt.Println(err, listoflists)
        for i, list := range listoflists {
            for j, value := range list {
                fmt.Println(i, j, value)
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致