strings.Split添加了额外的换行符。

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

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>

huangapple
  • 本文由 发表于 2021年12月3日 20:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/70214474.html
匿名

发表评论

匿名网友

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

确定