英文:
strings.Split adds additional newline
问题
使用ioutil.ReadFile
读取文件后,我尝试使用strings.Split
和分隔符\n
来拆分我的字节字符串,但是我收到了一个额外的换行符(切片的长度增加了+1
)。
为什么结果不如预期?
// numbers.txt
1
2
3
4
5
func main() {
data, _ := ioutil.ReadFile("numbers.txt")
input := strings.Split(string(data), "\n")
fmt.Println("Len: ", len(input))
for i, v := range input {
fmt.Println(i, v)
}
}
// Output
Len: 6
0 1
1 2
2 3
3 4
4 5
5
预期结果:
Len: 5
0 1
1 2
2 3
3 4
4 5
可能是重复的问题:Read text file into string array (and write)
请参考评论:
注意,当解析常规的POSIX文本文件时,
strings.Split
会附加一个额外的空行字符串 - bain Dec 1 '14 at 20:33
英文:
After reading file using ioutil.ReadFile
I try to split my "string" of bytes using strings.Split
and separator "\n"
, but I receive an extra newline (the length of slice is increased by + 1
).
Why is this not as expected?
// numbers.txt
1
2
3
4
5
func main() {
data, _ := ioutil.ReadFile("numbers.txt")
input := strings.Split(string(data), "\n")
fmt.Println("Len: ", len(input))
for i, v := range input {
fmt.Println(i, v)
}
}
// Output
Len: 6
0 1
1 2
2 3
3 4
4 5
5
Expected:
Len: 5
0 1
1 2
2 3
3 4
4 5
Could be duplicate of Read text file into string array (and write)
See comment
> Note strings.Split will append one extra line (an empty string) when
> parsing regular POSIX text files example – bain Dec 1 '14 at 20:33
答案1
得分: 3
strings.Split不会追加额外的行,否则文档中会有说明。如果你按照以下方式查看文件:
1\n
2\n
3\n
4\n
5\n
你会注意到,如果你按照\n
来分割字符串,那么应该有6个条目。
1\n2\n3\n4\n5\n<最后一个空项在这里>
英文:
strings.Split doesn't append an extra line - otherwise it would be specified in the documentation to it.
If you view your file as following:
1\n
2\n
3\n
4\n
5\n
You will notice, that there must be 6 entries if you split the string by \n
.
1\n2\n3\n4\n5\n<last empty item is here>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论