Exercise: Maps

Exercise: Maps

题目:

Implement WordCount. It should return a map of the counts of each “word” in the string s. 
The wc.Test function runs a test suite against the provided function and prints success or failure. You might find strings.Fields helpful.

代码:

import (
	"strings"
	"golang.org/x/tour/wc"
)

func WordCount(s string) map[string]int {
	m := make(map[string]int)
	//_s := make([]string, 0)
	//_s = strings.Split(s, " ")
    _s := strings.Fields(s)
	for _, value := range _s {
		//v, ok := m[value]
		//if ok {
		//	v += 1
		//} else {
		//	v = 1
		//}
		//m[value] = v
                m[value]++
	}
	return m
}

func main() {
	wc.Test(WordCount)
}        

  

  

结果:

PASS
 f("I am learning Go!") = 
  map[string]int{"am":1, "learning":1, "Go!":1, "I":1}
PASS
 f("The quick brown fox jumped over the lazy dog.") = 
  map[string]int{"dog.":1, "jumped":1, "over":1, "lazy":1, "fox":1, "the":1, "The":1, "quick":1, "brown":1}
PASS
 f("I ate a donut. Then I ate another donut.") = 
  map[string]int{"I":2, "ate":2, "a":1, "donut.":2, "Then":1, "another":1}
PASS
 f("A man a plan a canal panama.") = 
  map[string]int{"man":1, "a":2, "plan":1, "canal":1, "panama.":1, "A":1}

Program exited.

  

posted @ 2016-05-24 00:28  chpx  阅读(237)  评论(0编辑  收藏  举报