[ Golang을 배워보자! ] A Tour of Go - 41 연습: 맵 ( strings.Fields )steemCreated with Sketch.

in #golang7 years ago (edited)

안녕하세요.

이번에는 A Tour of Go 의 41번 문제를 해결해 보겠습니다.


주어진 문제는 이렇습니다.

strings.Fields 를 알면 어렵지않게 문제를 해결 할 수 있습니다.
물론 이 함수를 스스로 구현해 버릴 수도 있겠지만 귀찮은 작업이 되겠지요?

주어진 링크는 이렇습니다. http://golang.org/pkg/strings/#Fields
자 들어가보면

func Fields(s string) []string
Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning an array of substrings of s or an empty list if s contains only white space.

라고 설명이 나와있네요!

간단히 설명하자면 white space를 기준으로 문자열을 잘라서 배열 형태로 반환해 준다는 이야기네요.

그럼 우선... strings.Fields 함수를 사용하기위해 import 해줍니다.

import (
    "code.google.com/p/go-tour/wc"
    "strings"
)

그다음엔....

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

친절하게 잘라준 배열을 이용해 카운트를 해주는 것으로 문제는 쉽게 해결이 됩니다.

Coin Marketplace

STEEM 0.21
TRX 0.13
JST 0.029
BTC 67557.12
ETH 3500.56
USDT 1.00
SBD 2.70