英文:
How do you convert a string of ints to an array in Go?
问题
我无法在任何地方找到这个(或者我只是不理解)。我正在从一个以空格分隔的文件中读取一个数字列表。例如,文件看起来像“1 4 0 0 2 5 ...等等”,我希望它以数组的形式(或者更好的是,每一行都分开的二维数组)呈现。我该如何做到这一点?
这是我目前的代码 - 其中很多是从我找到的教程中获取的,所以我并不完全理解其中的所有内容。它可以很好地读取文件,并返回一个字符串。
附带问题:当我打印字符串时,输出的末尾会出现这个:%!(EXTRA
谢谢你能提供的任何帮助。
-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 (
"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
得分: 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
请注意,包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("sudoku1.txt")
if err != nil {
panic(err.String())
}
// split into rows at newlines
rows := strings.Split(s, "\n")
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论