A Tour of Go Exercise: Maps
2014-10-27 23:21
519 查看
Implement
You might find strings.Fields helpful.
WordCount. It should return a map of the counts of each “word” in the string
s. The
wc.Testfunction runs a test suite against the provided function and prints success or failure.
You might find strings.Fields helpful.
package main import ( "code.google.com/p/go-tour/wc" "strings" ) func WordCount(s string) map[string]int { m := make(map[string]int) strs := strings.Fields(s) for _,value := range strs { v, ok := m[value] if !ok { m[value] = 1 }else{ m[value] = v + 1 } } return m } func main() { wc.Test(WordCount) }
package main import ( "code.google.com/p/go-tour/wc" "strings" ) func WordCount(s string) map[string]int { m := make(map[string]int) strs := strings.Fields(s) for i := 0; i < len(strs); i++ { v, ok := m[strs[i]] if !ok { m[strs[i]] = 1 }else{ m[strs[i]] = v + 1 } } return m } func main() { wc.Test(WordCount) }
相关文章推荐
- A Tour of Go : Exercise: Maps
- 【GoLang笔记】A Tour of Go - Exercise: Images
- A Tour of Go : Exercise: Slices
- A Tour of Go Mutating Maps
- A Tour of Go: Exercise: Rot13 Reader
- A Tour of Go : Exercise: Fibonacci closure
- A Tour of Go : Advanced Exercise: Complex cube roots
- A Tour of Go Exercise: Images
- A Tour of Go---Exercise: Fibonacci closure
- A Tour of Go: Exercise: Rot13 Reader
- A Tour of Go - Exercise: Equivalent Binary Trees
- A Tour of Go Maps
- A Tour of Go - Exercise: Web Crawler
- 【GoLang笔记】A Tour of Go - Exercise: Web Crawler
- A Tour of Go : Exercise: Loops and Functions
- 【GoLang笔记】A Tour of Go - Exercise: Equivalent Binary Trees
- A Tour of Go If
- A Tour of Go Range continued
- A Tour of Go Map literals continued
- A Tour of Go If and else