dqq46733 2016-11-27 15:59
浏览 12
已采纳

拆分包括EOF?

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
", os.Args[0], err)
        continue
    }
    for _, line := range strings.Split(string(data), "
") {
        counts[line]++
    }
  }
  for line, n := range counts {
    if n > 1 {
        fmt.Printf("%d\t%s
", 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条回答 默认 最新

  • dongxiong2000 2016-11-27 16:59
    关注

    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
    World", "
    ")
    extraSlice := strings.Split("Hello
    World
    ", "
    ")
    
    // [Hello World] 2
    fmt.Println(eofSlice, len(eofSlice))
    
    // [Hello World ] 3
    fmt.Println(extraSlice, len(extraSlice))
    

    Playground link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么