Go语言学习笔记-A Tour of Go 练习笔记-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.

练习程序:

package main

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

var string_count_map map[string]int

func WordCount(s string) map[string]int {

    string_count_map = make(map[string]int)
	
	string_count := strings.Fields(s)
	for _, j := range string_count{
		ok := false
	    _, ok = string_count_map[j]
		if ok{
		    string_count_map[j] += 1
		}else{
		    string_count_map[j] = 1
		}
	}
	return string_count_map
}

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

运行结果:

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

笔记:该题目旨在通过Maps的创建和赋值,从而实现对String中单词的计数功能,通过利用string.Fields将一个字符串进行切分,得到单词slice, 讲该slice中的每个单词作为map的key值进行赋值,而map的value则根据单词出现的次数进行自增+1计数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值