英文:
split includes EOF?
问题
我正在尝试在Windows 7上使用Go版本1.7.3运行Donovan书中的gopl.io/ch1/dup3程序。
当我运行下面的test.go程序时,最后会得到一个空行。这是表示文件结束的标志吗?我该如何将其与实际的空行区分开来?
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文件运行命令:
> test.exe test.dat test.dat
输出结果为:
2 Line number one
2 Line number two
2 <-- 这是空行。
请注意,我只会返回翻译好的部分,不会回答关于翻译的问题。
英文:
I'm trying to run gopl.io/ch1/dup3 program from Donovan book on windows 7 using go version 1.7.3.
When I run the below program test.go, I get an empty line at the end. Is that for EOF? How do I distinguish it from an actual empty line?
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++
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
with test.dat file:
Line number one
Line number two
Command:
> test.exe test.dat test.dat
Output is
2 Line number one
2 Line number two
2 <-- Here is the empty line.
答案1
得分: 1
如果你的文件以换行序列结尾,将文件内容按换行序列进行拆分将导致多出一个空字符串。如果在读取最后一个换行序列之前发生了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))
英文:
If your file ends with a newline sequence, splitting the file content on newline sequences will result in an extraneous empty string. If EOF occurred before a final newline sequence was read, then you don't get that empty string:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论