Go語言程式查詢字串中字元的頻率


Go 語言中的字串是字元的集合。由於 Go 中的字串是不可變的,因此在生成後無法修改。但是,連線或新增到現有字串可以建立新的字串。字元的頻率是指字元出現的次數。

語法

map()

為了跟蹤輸入字串中每個字元出現的頻率,下面的示例使用了 Go 中內建的 map 資料結構。map 是一個無序的鍵值對集合,具有唯一的鍵和可變型別的值。

func make ([] type, size, capacity)

Go 語言中的 make 函式用於建立陣列/map,它接受要建立的變數型別、大小和容量作為引數。

演算法

  • 步驟 1 − 建立一個 package main 並宣告 fmt(格式化包)包。

  • 步驟 2 − 建立一個 main 函式,並在該函式中建立一個要計算字元頻率的字串。

  • 步驟 3 − 使用使用者定義或內部函式查詢字串中字元的頻率。

  • 步驟 4 − 使用 fmt.Println() 函式列印輸出,其中 ln 表示換行。

示例 1

在本例中,我們將學習如何使用 map 查詢字串中字元的頻率。這裡,map 將儲存字元的頻率,輸出將是一個列印每個字元頻率的 map。

package main
import (
	"fmt"
)

func main() {
	mystr := "hello alexa" //create a string
	fmt.Println("The string given here is:", mystr)
	frequency := make(map[rune]int)  //create frequency map using make function

	for _, val := range mystr {
		frequency[val]++ //assign frequencies 
	}

	fmt.Println("The frequency of characters in the string is:")

	fmt.Println(frequency)  //print frequency map
}

輸出

The string given here is: hello alexa
The frequency of characters in the string is:
map[120:1 104:1 101:2 108:3 111:1 32:1 97:2]

示例 2

在本例中,我們將學習如何使用 if-else 語句計算字串中字元的頻率。基本上,此條件語句將用於檢查頻率 map 中是否存在字元。

package main
import (
	"fmt"
)

func main() {
	mystr := "hello alexa"  //create string
	fmt.Println("The string given here is:", mystr)
	frequency := make(map[rune]int)  //create frequency map using make function

	for _, val := range mystr {
		if _, ok := frequency[val]; ok {
			frequency[val]++
		} else {
			frequency[val] = 1  //assign frequencies
		}
	}
	fmt.Println("The frequency of characters in the string is:")

	fmt.Println(frequency) //print frequency map
}

輸出

The string given here is: hello alexa
The frequency of characters in the string is:
map[97:2 120:1 104:1 101:2 108:3 111:1 32:1]

結論

我們使用兩種方法執行了列印字串中字元頻率的程式。在第一種方法中,我們使用了 map,在第二個示例中,我們使用了 if-else 條件語句以及 map。

更新於: 2023年2月1日

749 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告