练习:map
实现 WordCount
。它应当返回一个含有 s
中每个 “词” 个数的 map。函数wc.Test
针对这个函数执行一个测试用例,并输出成功还是失败.你会发现strings.Fields 很有帮助。
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
在题目中提示可以使用strings.Fields,那我们现在查一查这个函数
func Fields
func Fields(s string) []string
Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning an array of substrings of s or an empty list if s contains only white space.
看来还不错,这个函数对完成这个练习非常有帮助,通过介绍可以看出使用这个函数输入一个字符串,在内部使用空格将其分割,输出一个字符数组
这是练习给出的参考模版
package main
import (
"golang.org/x/tour/wc"
)
func WordCount(s string) map[string]int {
return map[string]int{"x": 1}
}
func main() {
wc.Test(WordCount)
}
下面是实现的代码,经过验证可以通过
题外话:觉得Go指南真的做得很用心呀,运行给出的结果非常清楚直接
package main
import (
"fmt"
"strings"
)
func main(){
s := "I love my work and I"
res := WordCount(s)
fmt.Println(res)
}
func WordCount(s string) map[string]int {
s_arr := strings.Fields(s)//分割字符串为字符数组
s_map := make(map[string]int)//建立map
//对s_arr中的每个字符进行循环
for i:= 0; i<len(s_arr); i++ {
if s_map[s_arr[i]] == 0 { //当还没有统计过该字符时,赋值为1
s_map[s_arr[i]] = 1
} else { //当统计过该字符时,更新计数值+1
s_map[s_arr[i]] = s_map[s_arr[i]] + 1
}
}
return s_map
}