学习 go 语言一个字符串切片问题,求帮助

2018-09-08 23:42:28 +08:00
 nzzzg

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 个

2172 次点击
所在节点    Go 编程语言
2 条回复
eote
2018-09-08 23:46:45 +08:00
Windows 换行符是\r\n
nzzzg
2018-09-08 23:50:14 +08:00
@eote 还真是,已解决,thx

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/487505

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX