One more tour of go exercise.
authorsgf <sgf.dma@gmail.com>
Tue, 21 Jun 2022 21:21:31 +0000 (00:21 +0300)
committersgf <sgf.dma@gmail.com>
Tue, 21 Jun 2022 21:21:31 +0000 (00:21 +0300)
wc.go [new file with mode: 0644]

diff --git a/wc.go b/wc.go
new file mode 100644 (file)
index 0000000..2fcc695
--- /dev/null
+++ b/wc.go
@@ -0,0 +1,37 @@
+package main
+
+import (
+       "golang.org/x/tour/wc"
+       "unicode"
+)
+
+func AddWord(w string, r map[string]int) {
+       if w == "" {
+               return
+       }
+       if _, ok := r[w]; ok {
+               r[w]++
+       } else {
+               r[w] = 1
+       }
+}
+func WordCount(s string) map[string]int {
+       w := ""
+       r := make(map[string]int)
+       for _, c := range s {
+               if unicode.IsSpace(c) {
+                       AddWord(w, r)
+                       w = ""
+                       continue
+               }
+               w += string(c)
+       }
+       AddWord(w, r)
+
+       return r
+}
+
+func main() {
+       wc.Test(WordCount)
+}
+