go统计字符串及数组中出现次数
数组:统计出现字数 package main import "fmt" func main() { s := [...]string{"Mlxg", "123","Mlxg", "abc" ,"fff" ,"123", "Mlxg", "fff", "abc", "123", "abc", "fff"} m := make(map[string]int, 20) //定义map //遍历数组存储到map for _,v := range s{ //遍历数组s,map比较 if _,ok := m[v]; ok { //判断是否第一次出现 m[v] ++ //否,m[v]值加1 }else { m[v] = 1 //第一次出现存储到map,m[v]=1 } } for i,v := range m{ //遍历map fmt.Println(i,v) } fmt.Println(m,len(m)) fmt.Println(s,len(s),cap(s)) }
package main import ( "fmt" "strings" ) func main() { s := "Tom abc Lucy Lily Lucy Lucy Cat Dog Pig Lucy Tom" s1 := strings.Split(s, " ") //将字符串按空格切割,得到切片 m1 := make(map[string]int, 20) //遍历切片存储到map for _,k := range s1{ //遍历切片,map比较 if _,ok := m1[k]; ok { m1[k] ++ } else { m1[k] = 1 } } for i,v := range m1{ fmt.Println(i,v) } }