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

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

strings.Split adds additional newline

问题

使用ioutil.ReadFile读取文件后,我尝试使用strings.Split和分隔符\n来拆分我的字节字符串,但是我收到了一个额外的换行符(切片的长度增加了+1)。

为什么结果不如预期?

  1. // numbers.txt
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  1. func main() {
  2. data, _ := ioutil.ReadFile("numbers.txt")
  3. input := strings.Split(string(data), "\n")
  4. fmt.Println("Len: ", len(input))
  5. for i, v := range input {
  6. fmt.Println(i, v)
  7. }
  8. }
  9. // Output
  10. Len: 6
  11. 0 1
  12. 1 2
  13. 2 3
  14. 3 4
  15. 4 5
  16. 5

预期结果:

  1. Len: 5
  2. 0 1
  3. 1 2
  4. 2 3
  5. 3 4
  6. 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?

  1. // numbers.txt
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  1. func main() {
  2. data, _ := ioutil.ReadFile("numbers.txt")
  3. input := strings.Split(string(data), "\n")
  4. fmt.Println("Len: ", len(input))
  5. for i, v := range input {
  6. fmt.Println(i, v)
  7. }
  8. }
  9. // Output
  10. Len: 6
  11. 0 1
  12. 1 2
  13. 2 3
  14. 3 4
  15. 4 5
  16. 5

Expected:

  1. Len: 5
  2. 0 1
  3. 1 2
  4. 2 3
  5. 3 4
  6. 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. 1\n
  2. 2\n
  3. 3\n
  4. 4\n
  5. 5\n

你会注意到,如果你按照\n来分割字符串,那么应该有6个条目。

  1. 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. 1\n
  2. 2\n
  3. 3\n
  4. 4\n
  5. 5\n

You will notice, that there must be 6 entries if you split the string by \n.

  1. 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:

确定