码迷,mamicode.com
首页 > 其他好文 > 详细

Exercise: Maps

时间:2016-05-24 01:47:25      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

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
	}
	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.

  

Exercise: Maps

标签:

原文地址:http://www.cnblogs.com/chpx/p/5522050.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!