👻創作者:丶重明
👻創作時間:2025年3月9日
👻擅長領域:運維
目錄
- 1.😶?🌫?題目:統計字符出現的次數
- 2.😶?🌫?代碼中可用的資源
- 3.😶?🌫?代碼開發過程
- 4.😶?🌫?代碼輸出結果
- 5.😶?🌫?代碼解析
- 6.😶?🌫?內容擴展
1.😶?🌫?題目:統計字符出現的次數
編寫一個 Go 函數,接收一個字符串,返回該字符串中每個字符出現的次數,返回值為一個映射(map)類型。
2.😶?🌫?代碼中可用的資源
dwadaw達瓦官方阿迪王迪王是是是哇
3.😶?🌫?代碼開發過程
通過Go語言開發,以下是完整代碼。
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
命令執行代碼。
> 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
視為一個單詞 - 忽略文中的標點符號
- 按出現次數的多少進行排序
同系列:
上一篇:【Go每日一練】返回切片中的最大值和最小值