👻创作者:丶重明
👻创作时间:2025年3月9日
👻擅长领域:运维
目录
- 1.😶🌫️题目:
- 2.😶🌫️资源:
- 3.😶🌫️代码:
- 4.😶🌫️输出:
- 5.😶🌫️解析:
- 6.😶🌫️扩展:
1.😶🌫️题目:
编写一个 Go 函数,接收一个字符串,返回该字符串中每个字符出现的次数,返回值为一个映射(map)类型。
2.😶🌫️资源:
dwadaw达瓦官方阿迪王迪王是是是哇
3.😶🌫️代码:
package mainimport ("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 mainimport ("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
其他扩展方向,请自行尝试:
- 从外部导入文件并统计
- 大小写标准化,比如
hello
和HELLO
视为一个单词 - 忽略文中的标点符号
- 按出现次数的多少进行排序