如何将一个由整数组成的字符串转换为Go中的数组?

huangapple go评论89阅读模式
英文:

How do you convert a string of ints to an array in Go?

问题

我无法在任何地方找到这个(或者我只是不理解)。我正在从一个以空格分隔的文件中读取一个数字列表。例如,文件看起来像“1 4 0 0 2 5 ...等等”,我希望它以数组的形式(或者更好的是,每一行都分开的二维数组)呈现。我该如何做到这一点?

这是我目前的代码 - 其中很多是从我找到的教程中获取的,所以我并不完全理解其中的所有内容。它可以很好地读取文件,并返回一个字符串。
附带问题:当我打印字符串时,输出的末尾会出现这个:%!(EXTRA )。有人知道如何修复这个问题吗?我猜它是将最后一个nil字符放在返回字符串中,但我不知道如何修复它。

谢谢你能提供的任何帮助。

-W

英文:

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 <nil>)
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 (
  &quot;fmt&quot;
  &quot;os&quot;
)

func read_file(filename string) (string, os.Error) {
  f, err := os.Open(filename)
  if err != nil {
    return &quot;&quot;, err
  }
  defer f.Close()  // f.Close will run when we&#39;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 &quot;&quot;, 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(&quot;sudoku1.txt&quot;)) // this outputs the file exactly, 
                                      // but with %!(EXTRA &lt;nil&gt;) at the end. 
                                      // I do not know why exactly
}

Thank you very much for any help you can offer.

-W

答案1

得分: 6

你可以使用strings包将字符串转换为一个二维整数数组。解释这里使用的一些语言结构超出了这个问题的范围,但是请随时要求澄清任何问题。

// read_file也返回一个错误!
s, err := read_file("sudoku1.txt")
if err != nil {
panic(err.String())
}

// 在换行符处拆分为行
rows := strings.Split(s, "\n")
board := make([][]int, len(rows))
for i, row := range rows {
// 提取所有以空格分隔的字段
elems := strings.Fields(row)
board[i] = make([]int, len(elems))
for j, elem := range elems {
var err os.Error
// 将每个元素转换为整数
board[i][j], err = strconv.Atoi(elem)
if err != nil {
panic(err.String())
}
}
}
fmt.Println(board)

"%(!EXTRA )"的原因是read_file返回两个值,第二个是一个错误(在这种情况下为nil)。Printf尝试将第二个值与字符串中的一个位置匹配。由于字符串中不包含任何格式化位置(%v,%d,%s...),Printf确定它是一个额外的参数,并在输出中表示。

请注意,包ioutil已经提供了一个ReadFile函数,它将给你一个[]byte而不是一个字符串,但在功能上与你的read_file函数相同。

英文:

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(&quot;sudoku1.txt&quot;)
if err != nil {
	panic(err.String())
}

// split into rows at newlines
rows := strings.Split(s, &quot;\n&quot;)
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 &lt;nil&gt;) 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.

huangapple
  • 本文由 发表于 2011年11月24日 02:02:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/8246946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定