Go指南中的練習:map

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

練習:map

實現 WordCount。它應當返回一個含有 s 中每個 “詞” 個數的 map。函數wc.Test 針對這個函數執行一個測試案例,並輸出成功還是失敗.你會發現strings.Fields 很有協助。

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

在題目中提示可以使用strings.Fields,那我們現在查一查這個函數


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

看來還不錯,這個函數對完成這個練習非常有協助,通過介紹可以看出使用這個函數輸入一個字串,在內部使用空格將其分割,輸出一個字元數組


這是練習給出的參考模版

package mainimport ("golang.org/x/tour/wc")func WordCount(s string) map[string]int {return map[string]int{"x": 1}}func main() {wc.Test(WordCount)}


下面是實現的代碼,經過驗證可以通過

題外話:覺得Go指南真的做得很用心呀,運行給出的結果非常清楚直接

package mainimport ("fmt""strings")func main(){s := "I love my work and I"res := WordCount(s)fmt.Println(res)}func WordCount(s string) map[string]int {s_arr := strings.Fields(s)//分割字串為字元數組s_map := make(map[string]int)//建立map//對s_arr中的每個字元進行迴圈for i:= 0; i<len(s_arr); i++ {if s_map[s_arr[i]] == 0 { //當還沒有統計過該字元時,賦值為1s_map[s_arr[i]] = 1} else {                  //當統計過該字元時,更新計數值+1s_map[s_arr[i]] = s_map[s_arr[i]] + 1}}return s_map}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.