dongmao3131 2011-11-23 18:02
浏览 198
已采纳

如何在Go中将整数字符串转换为数组?

I haven't been able to find this anywhere (or I just don't understand it). I'm reading in a list of numbers from a file separated by spaces. I.e. the file looks like "1 4 0 0 2 5 ...etc", and I want it in the form of an array (or, preferably, a 2 dimensional array where each new line is separated as well). How might I go about doing this?

This is the code I have so far - a lot of it is taken from tutorials I found, so I don't fully understand all of it. It reads in a file just fine, and returns a string. Side question: when I print the string, I get this at the end of the output: %!(EXTRA ) Does anyone know how to fix that? I'm assuming it's putting the last nil character in the return string, but I don't know how to fix that.

package main
import (
  "fmt"
  "os"
)

func read_file(filename string) (string, os.Error) {
  f, err := os.Open(filename)
  if err != nil {
    return "", err
  }
  defer f.Close()  // f.Close will run when we're finished.

  var result []byte
  buf := make([]byte, 100)
  for {
    n, err := f.Read(buf[0:])
    result = append(result, buf[0:n]...) // append is discussed later.
    if err != nil {
      if err == os.EOF {
        break
      }
    return "", err  // f will be closed if we return here.
    }
  }
  return string(result), nil // f will be closed if we return here.
}

func print_board() {

}

func main() {
 fmt.Printf(read_file("sudoku1.txt")) // this outputs the file exactly, 
                                      // but with %!(EXTRA <nil>) at the end. 
                                      // I do not know why exactly
}

Thank you very much for any help you can offer.

-W

  • 写回答

1条回答 默认 最新

  • duane9322 2011-11-23 19:26
    关注

    You can use the strings package to convert the string to a 2 dimensional array of ints. Explaining some of the language constructs used here is a bit outside the scope of this question, but feel free to ask for clarification on anything.

    // read_file also returns an error!
    s, err := read_file("sudoku1.txt")
    if err != nil {
        panic(err.String())
    }
    
    // split into rows at newlines
    rows := strings.Split(s, "
    ")
    board := make([][]int, len(rows))
    for i, row := range rows {
        // extract all whitespace separated fields
        elems := strings.Fields(row)
        board[i] = make([]int, len(elems))
        for j, elem := range elems {
            var err os.Error
                // convert each element to an integer
            board[i][j], err = strconv.Atoi(elem)
            if err != nil {
                panic(err.String())
            }
        }
    }
    fmt.Println(board)
    

    The reason for the %(!EXTRA <nil>) is that read_file returns two values, the second being an error (which is nil in this case). Printf tries to match that second value to a slot in the string. Since the string doesn't contain any formatting slots (%v, %d, %s...), Printf determines that it is an extra parameter, and says that in the output.

    Note that the package ioutil already provides a ReadFile function, which will give you a []byte instead of a string, but is otherwise identical in function to your read_file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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