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