V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
nzzzg
V2EX  ›  Go 编程语言

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

  •  
  •   nzzzg · 2018-09-08 23:42:28 +08:00 · 2147 次点击
    这是一个创建于 2028 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 个

    eote
        1
    eote  
       2018-09-08 23:46:45 +08:00
    Windows 换行符是\r\n
    nzzzg
        2
    nzzzg  
    OP
       2018-09-08 23:50:14 +08:00
    @eote 还真是,已解决,thx
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1402 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:30 · PVG 01:30 · LAX 10:30 · JFK 13:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.