-1

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

N. J
  • 398
  • 2
  • 13
  • 3
    Use [`bytes.TrimSpace`](https://pkg.go.dev/bytes@go1.17.3#TrimSpace) on `data` or [`strings.TrimSpace`](https://pkg.go.dev/strings@go1.17.3#TrimSpace) on `string(data)` before splitting it. See: https://go.dev/play/p/E5Hq0Lbojsy – mkopriva Dec 03 '21 at 13:02
  • Nice I'll use this. – N. J Dec 03 '21 at 13:33

1 Answers1

3

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>
Vüsal
  • 2,580
  • 1
  • 12
  • 31