方法一:先统计,然后根据key进行排序输出
str := "ERWQREEIUWQJNCDSCMKLSADASDPSADOPISAPD"
map1 := make(map[int]int)
for i := 0; i < len(str); i++ {
if map1[int(str[i])] == 0 {
map1[int(str[i])] = 1
} else if map1[int(str[i])] > 0 {
num := map1[int(str[i])]
map1[int(str[i])] = num + 1
}
}
for key,count:= range map1 {
fmt.Printf("%c : %d \n",key,count)
}
keys := make([]int, 0, len(map1))
for key := range map1 {
keys = append(keys, int(key))
}
sort.Ints(keys)
for _ ,key := range keys {
fmt.Printf("%c : %d \n",key,map1[key])
}
方法二:限制了必须是纯字母的字符串
for i := 'A'; i <= 'Z'; i++ {
count := 0
for j := 0; j < len(str); j++ {
if i == int32(str[j]) {
count++
}
}
if count > 0 {
fmt.Printf("%c : %d \n", i, count)
}
}
方法三:也是限制了必须是纯字母的字符串,i是rune类型 需要转换成string
for i:='A';i<='Z'; i++ {
fmt.Printf("%s : %d \n",string(i),strings.Count(str,string(i)))
}
有疑问加站长微信联系(非本文作者)