go查询长字符串词语数量
点击查看代码
package main
import (
"fmt"
"strings"
)
func statWordCount(str string) map[string]int {
var result map[string]int = make(map[string]int,128)
words := strings.Split(str," ")
fmt.Printf("你好啊words>> words=%v \n",words)
for _, v := range words{
count, ok := result[v]
fmt.Printf("你好啊count>> count=%v ok=%v v=%v\n",count,ok,v)
if !ok{
result[v] = 1
}else{
result[v] = count+1
}
}
return result
}
func main() {
var str ="how do you do ? do you like me ?"
result := statWordCount(str)
fmt.Printf("result: %#v\n",result)
}
输出:
点击查看代码
``` 你好啊words>> words=[how do you do ? do you like me ?] 你好啊count>> count=0 ok=false v=how 你好啊count>> count=0 ok=false v=do 你好啊count>> count=0 ok=false v=you 你好啊count>> count=1 ok=true v=do 你好啊count>> count=0 ok=false v=? 你好啊count>> count=2 ok=true v=do 你好啊count>> count=1 ok=true v=you 你好啊count>> count=0 ok=false v=like 你好啊count>> count=0 ok=false v=me 你好啊count>> count=1 ok=true v=? result: map[string]int{"?":2, "do":3, "how":1, "like":1, "me":1, "you":2} ```
写入自己的博客中才能记得长久