Go 語言程式:將字串集合轉換為字串陣列
在本教程中,我們將編寫一個 Go 語言程式,用於將一組字串轉換為字串陣列。在 Go 中,集合是一種抽象資料型別,可以儲存特定值而不會重複任何值,並且沒有特定的順序。
使用內建函式將字串集合轉換為字串陣列
下面給出使用 Go 程式語言中預定義函式將字串集合轉換為字串陣列的程式。
語法
func make([]type, length, capacity) []type
make 函式用於建立切片或對映。它接受三個引數:一個是我們要建立的切片名稱和型別,然後是切片的長度和容量。該函式然後返回最終的切片。
func len(v Type) int
len() 函式用於獲取任何引數的長度。它接受一個引數作為我們要查詢其長度的資料型別變數,並返回一個整數作為變數的長度。
演算法
步驟 1 - 匯入 fmt 包。
步驟 2 - 現在開始 main 函式。
步驟 3 - 使用 make() 函式建立一個新集合並向其中新增值。
步驟 4 - 使用 fmt.Println() 函式在螢幕上列印集合。
步驟 5 - 現在建立一個字串型別的陣列。
步驟 6 - 將集合的長度儲存在一個 int 型別的變數中。使用從 0 到集合長度的 for 迴圈迭代陣列。
步驟 7 - 在每次迭代中,將集合中的值儲存到陣列中,並重復此過程,直到整個集合複製到陣列中。
步驟 8 - 最後,我們需要使用 fmt.Println() 函式在螢幕上列印陣列。
示例
package main
import (
"fmt"
)
func main() {
newset := make(map[int]string)
newset[0] = "Sunday"
newset[1] = "Monday"
newset[2] = "Tuesday"
fmt.Println("The obtained set is:", newset)
var arr [3]string
v := len(newset)
for i := 0; i < v; i++ {
arr[i] = newset[i]
}
fmt.Println("The array obtained from the set is:", arr)
}
輸出
The obtained set is: map[1:Monday 2:Tuesday 0:Sunday] The array obtained from the set is: [Sunday Monday Tuesday]
使用外部函式將字串集合轉換為字串陣列
現在讓我們編寫一個 Go 語言程式,使用外部函式將一組字串轉換為字串陣列。
演算法
步驟 1 - 匯入 fmt 包。
步驟 2 - 建立一個函式 setToStrings() 來將給定的集合轉換為陣列。
步驟 3 - 現在開始 main 函式。
步驟 4 - 使用 make() 函式建立一個新集合並向其中新增值。
步驟 5 - 使用 fmt.Println() 函式在螢幕上列印集合。
步驟 6 - 透過將對映變數作為引數傳遞給函式來呼叫 setToString() 函式。
步驟 7 - 現在建立一個字串型別的陣列。
步驟 8 - 將集合的長度儲存在一個 int 型別的變數中。使用從 0 到集合長度的 for 迴圈迭代陣列。
步驟 9 - 在每次迭代中,將集合中的值儲存到陣列中,並重復此過程,直到整個集合複製到陣列中。
步驟 10 - 從函式中返回陣列並將其儲存在一個名為 output 的變數中。
步驟 11 - 最後,我們需要使用 fmt.Println() 函式在螢幕上列印陣列。
示例
package main
import (
"fmt"
)
func setToString(newset map[int]string) [3]string {
var arr [3]string
v := len(newset)
for i := 0; i < v; i++ {
arr[i] = newset[i]
}
return arr
}
func main() {
newset := make(map[int]string)
newset[0] = "Apple"
newset[1] = "Mango"
newset[2] = "Banana"
fmt.Println("The obtained set is:", newset)
output := setToString(newset)
fmt.Println("The array obtained from the set is:", output)
}
輸出
The obtained set is: map[0:Apple 1:Mango 2:Banana] The array obtained from the set is: [Apple Mango Banana]
結論
我們已經成功編譯並執行了一個 Go 語言程式碼,用於將一組字串轉換為字串陣列,並附帶示例。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP