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.

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

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch