编写程序,统计字符串中每个字符的出现次数 golang
时间: 2023-11-14 14:05:44 浏览: 46
以下是一个简单的程序,可以统计一个字符串中每个字符的出现次数:
```
package main
import (
"fmt"
)
func countChars(s string) map[rune]int {
counts := make(map[rune]int)
for _, c := range s {
counts[c]++
}
return counts
}
func main() {
s := "Hello, world!"
counts := countChars(s)
for c, count := range counts {
fmt.Printf("%c: %d\n", c, count)
}
}
```
在这个程序中,`countChars` 函数接受一个字符串作为参数,并返回一个 `map`,其中每个字符都是一个键,对应的值是该字符在字符串中出现的次数。该函数使用一个 `for` 循环遍历字符串的每个字符,并在 `counts` 映射中增加对应的计数器。最后,`counts` 映射被返回给调用者。
在 `main` 函数中,我们定义了一个字符串 `s`,并调用 `countChars` 函数来获取字符计数器的映射。然后,我们使用一个 `for` 循环遍历 `counts` 映射,并打印每个字符以及它在字符串中出现的次数。注意,我们使用 `%c` 格式化字符串来打印字符,而不是使用 `%s`,因为 `%c` 可以打印 Unicode 字符。