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

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

    点赞 评论

相关推荐 更多相似问题