You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
598 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"fmt"
"sort"
"strings"
)
/**
*写一个程序统计一个字符串中每个单词出现的次数。比如”how do you do”中how=1 do=2 you=1。
*/
func main() {
str := "how do you do"
strMap := make(map[string]int, 10)
strSlice := strings.Split(str, " ")
for _, value := range strSlice {
_, ok := strMap[value]
if ok {
strMap[value]++
} else {
strMap[value] = 1
}
}
keys := []string{}
for key := range strMap {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Printf("%v: %v ", key, strMap[key])
}
}