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 语言代码,用于将一组字符串转换为字符串数组,并附带示例。

更新于: 2022-12-28

2K+ 阅读量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.