57

go指南:映射练习

 4 years ago
source link: https://studygolang.com/articles/20356?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

题目

题目地址 https://tour.go-zh.org/moretypes/23

练习:映射

实现 WordCount 。它应当返回一个映射,其中包含字符串 s 中每个“单词”的个数。函数 wc.Test 会对此函数执行一系列测试用例,并输出成功还是失败。

你会发现 strings.Fields 很有帮助。

答案

package main

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

func WordCount(s string) map[string]int {
    sFields := strings.Fields(s)
    var resMap = map[string]int{}
    for _,v := range sFields{
        resMap[v] ++
    }
    return resMap
}

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

分析

String.Fields

按我的理解就是 将一个字符串,以空格为分隔符,分割为数组。

思路

然后将传过来的字符串拆分为数组后,将对应的Map对应key的值进行+1操作,这里的技巧是没有初始化的key,默认值为0.

降低IDE的Unused错误等级

话说用intellij的IDE goland,会经常报Unused错误,就是说没用使用,但问题我只是还没写完,然后因为是初学golang,以为是什么了不起的错误,就很浪费时间。

如图可以将其改为Warning,Ctrl+Alt+S 打开设置

bIjI7fR.png!web

IDE配置

还可以用Ctrl+Shift+A,进行搜索,如图

qARRj2e.png!web

image.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK