我正在尝试解决来自 go tour #23 的难题而且我不明白为什么我的单词计数器不起作用。 print
似乎打印出预期值,但测试只看到 1
而不管计数。
package main
import (
"strings"
"unicode/utf8"
"golang.org/x/tour/wc"
)
func WordCount(s string) map[string]int {
// explode the string into a slice without whitespaces
ws := strings.Fields(s)
//make a new map
c := make(map[string]int)
//iterate over each word
for _, v := range ws {
c[v] = utf8.RuneCountInString(v)
}
print(c["am"])
return c
}
func main() {
wc.Test(WordCount)
}
Playground 可用here
最佳答案
您正在解决错误的问题。它不会问你每个单词的长度,而是每个单词出现的次数。改变
c[v] = utf8.RuneCountInString(v)
对于
c[v] += 1 // or c[v]++
关于go - Go 练习之旅 #23 : my word counter doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22632594/