split包括EOF吗?

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

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 (
  &quot;fmt&quot;
  &quot;io/ioutil&quot;
  &quot;os&quot;
  &quot;strings&quot;
)
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, &quot;%s: %v\n&quot;, os.Args[0], err)
		continue
	}
	for _, line := range strings.Split(string(data), &quot;\r\n&quot;) {
		counts
++ } } for line, n := range counts { if n &gt; 1 { fmt.Printf(&quot;%d\t%s\n&quot;, n, line) } } }

with test.dat file:

Line number one
Line number two

Command:

&gt; test.exe test.dat test.dat

Output is

2       Line number one  
2       Line number two  
2                           &lt;-- 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))

Playground链接

英文:

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(&quot;Hello\r\nWorld&quot;, &quot;\r\n&quot;)
extraSlice := strings.Split(&quot;Hello\r\nWorld\r\n&quot;, &quot;\r\n&quot;)

// [Hello World] 2
fmt.Println(eofSlice, len(eofSlice))

// [Hello World ] 3
fmt.Println(extraSlice, len(extraSlice))

Playground link

huangapple
  • 本文由 发表于 2016年11月27日 23:59:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/40830868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定