main.go 包内容
package main import ( "fmt" "os" "io/ioutil" "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,"errMsg:%v\n",err) } for _,line := range strings.Split(string(data),"\n"){ counts[line]++ } } for line,n := range counts{ fmt.Printf("%d\t%s\n",n,line) } }
1.txt 内容如下:
123 456 123 hello hello
运行 go run main.go 1.txt ,显示结果如下:
2 123 1 456 1 hello 1 hello
到这里就蒙了,1.txt 里面 hello 是两行,为什么存到 map 里面的时候是分成两个来存储的?而且如果在 1.txt 里面最后一个 hello 后面加一个回车,map 里面 hello 的数量就是 2 个
![]() | 1 eote 2018-09-08 23:46:45 +08:00 Windows 换行符是\r\n |