我试图使用go版本1.7.3从windows 7上的Donovan图书中运行gopl.io/ch1/dup3 3程序。
当我运行下面的程序test.go时,在最后得到一个空行。是给EOF的吗?如何将它与实际的空行区分开来?
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
Counts := make(map[string]int)
for _, filename := range os.Args[1:] {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", os.Args[0], err)
continue
}
for _, line := range strings.Split(string(data), "\r\n") {
counts[line]++
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}使用test.dat文件:
Line number one
Line number two命令:
> test.exe test.dat test.dat输出是
2 Line number one
2 Line number two
2 <-- Here is the empty line.发布于 2016-11-27 16:59:36
如果您的文件以换行符结束,那么将文件内容拆分到换行符上将导致一个无关的空字符串。如果EOF发生在读取最后换行符序列之前,则不会得到该空字符串:
eofSlice := strings.Split("Hello\r\nWorld", "\r\n")
extraSlice := strings.Split("Hello\r\nWorld\r\n", "\r\n")
// [Hello World] 2
fmt.Println(eofSlice, len(eofSlice))
// [Hello World ] 3
fmt.Println(extraSlice, len(extraSlice))https://stackoverflow.com/questions/40830868
复制相似问题