【Go】统计单词个数

package main 

import (
	"fmt"
	"os"
	"bufio"
	"strings"
)

func receiveStringsFromStdin() string {
	fmt.Printf("请输入一个字符串: ")
	reader := bufio.NewReader(os.Stdin)
	r, _ := reader.ReadString('\n')
	return r
}

func main() {
	var (
		s string
		count map[string]int
	)
	count = make(map[string]int)
	s = receiveStringsFromStdin()
	//fmt.Printf("输入的字符串为: %s", s)
	strArr := strings.Fields(s)
	for _, v := range strArr {
		_, e := count[v]
		if !e {
			count[v] = 1
		} else {
			count[v]++ 
		}
	}

	for k, v := range count {
		fmt.Printf("%s: %d次\n", k, v)
	}
}

  

posted @ 2022-05-09 11:50  kunsile  阅读(80)  评论(0编辑  收藏  举报