V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
nzzzg

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

  •  
  •   nzzzg · Sep 8, 2018 · 2964 views
    This topic created in 2794 days ago, the information mentioned may be changed or developed.

    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  
       Sep 8, 2018
    Windows 换行符是\r\n
    nzzzg
        2
    nzzzg  
    OP
       Sep 8, 2018
    @eote 还真是,已解决,thx
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   830 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 20:14 · PVG 04:14 · LAX 13:14 · JFK 16:14
    ♥ Do have faith in what you're doing.