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

如何在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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?