【Go每日一练】统计字符出现的次数

发布于:2025-03-11 ⋅ 阅读:(16) ⋅ 点赞:(0)

👻创作者:丶重明
👻创作时间:2025年3月9日
👻擅长领域:运维

1.😶‍🌫️题目:

编写一个 Go 函数,接收一个字符串,返回该字符串中每个字符出现的次数,返回值为一个映射(map)类型。

2.😶‍🌫️资源:

dwadaw达瓦官方阿迪王迪王是是是哇

3.😶‍🌫️代码:

package main

import (
	"fmt"
)

func countCharacters(s string) map[rune]int {
	charCount := make(map[rune]int)

	for _, char := range s {
		charCount[char]++
	}
	return charCount
}
func main() {
	input := "dwadaw达瓦官方阿迪王迪王是是是哇"
	counts := countCharacters(input)

	for char, count := range counts {
		fmt.Printf("'%c': %d\n", char, count)
	}
}

4.😶‍🌫️输出:

> go run .\4.gotest.go
'阿': 1
'王': 2
'w': 2
'a': 2
'达': 1
'瓦': 1
'官': 1
'方': 1
'迪': 2
'是': 3
'd': 2
'哇': 1

5.😶‍🌫️解析:

func countCharacters(s string) map[rune]int {...}

定义一个名为countCharacters的函数,接收一个字符串s作为参数,并返回一个map[rune]int类型的结果

map[rune]int表示一个键为rune类型,值为 int类型的映射

rune表示一个 Unicode 码点,用于处理Unicode 字符(如中文、表情符号等)

   charCount := make(map[rune]int)

使用make创建一个空的map[rune]int类型的映射charCount,用于储存每个字符及出现的次数

    for _, char := range s {
        charCount[char]++
    }

使用for循环遍历字符串s中的每个字符

charCount[char]++对当前字符char在映射charCount中的计数加1

	input := "dwadaw达瓦官方阿迪王迪王是是是哇"
	counts := countCharacters(input)

定义一个字符串类型的变量input,其初始值为“ ”内内容

调用函数countCharacters将字符串input作为参数传入,将返回的值赋值给变量counts

    for char, count := range counts {
        fmt.Printf("'%c': %d\n", char, count)
    }

使用for...range遍历counts映射中的每个键值对,其中char是字符,count是出现的次数

然后使用fmt.Printf将字符和出现的次数打印出来

6.😶‍🌫️扩展:

如果有一段话是英文句子,该怎么统计:

hello world, go python java go world world

代码:

package main

import (
	"fmt"
	"strings"
)

func countCharacters(s string) map[string]int {
	wordCount := make(map[string]int)
	// 将字符串以空白为分隔符分区
	words := strings.Fields(s)

	for _, word := range words {
		wordCount[word]++
	}
	return wordCount
}
func main() {
	input := "hello world, go python java go world world"
	counts := countCharacters(input)

	for word, count := range counts {
		fmt.Printf("\"%s\": %d\n", word, count)
	}
}

输出:

> go run .\4.gotest.go
"world,": 1
"go": 2
"python": 1
"java": 1
"world": 2
"hello": 1

其他扩展方向,请自行尝试:

  • 从外部导入文件并统计
  • 大小写标准化,比如helloHELLO视为一个单词
  • 忽略文中的标点符号
  • 按出现次数的多少进行排序