go語言MAP用法

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

先做一個練習題:http://tour.golangtc.com/moretypes/18

練習:map

實現 `WordCount`。它應當返回一個含有 s 中每個 “詞” 個數的 map。函數 wc.Test 針對這個函數執行一個測試案例,並列印成功或者失敗。

你會發現 strings.Fields 很有協助。

My Code:

package mainimport (    "code.google.com/p/go-tour/wc"    "strings"    )func WordCount(s string) map[string]int {     str := strings.Fields(s)//把字串分成單詞數組  m := make(map[string]int)  for i:=0;i<len(str);i++{if m[str[i]]==0{  m[str[i]]=1}else{  m[str[i]]++}  }return m}func main() {wc.Test(WordCount)}
運行結果:

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



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.