如何在Golang中将字符串转换为数组?

huangapple go评论81阅读模式
英文:

How to convert a string to an array in Golang?

问题

如何在Go中有效地将字符串转换为只包含一个元素(即该字符串)的字符串数组。

例如:

var s string
s = "This is a string"

转换为

["This is a string"]

显然,一种方法是创建一个字符串数组,并将第一个元素初始化为该字符串,但我正在寻找一种更有效的方法。

英文:

How to convert a string to an array of strings with one element (i.e. that string) in Go effectively.

For example:

var s string
s = "This is a string"

to

["This is a string"]

Obviously, one way would be to make an array of strings and initialize the first element as that string but I am looking for an effective approach.

答案1

得分: 14

在Go语言中,要初始化一个字符串切片,你可以使用s := []string{"This is a string"}
要初始化一个字符串数组,你可以使用s := [1]string{"This is a string"}

唯一的区别在于是否指定数组的长度。

要了解你想要使用哪种结构,你应该阅读更多关于切片数组之间的区别,可以在Go博客上阅读更多相关信息(https://blog.golang.org/go-slices-usage-and-internals)。

英文:

To initialize a string slice in Go, you use s := []string{"This is a string"}.
To initialize a string array in Go, you use s := [1]string{"This is a string"}.

The only difference (in declaring each) lies in specifying the array length or not.

To understand which structure you want to use, you should read more about the difference between slices and arrays on the Go Blog.

答案2

得分: 0

你可以阅读Go Blog上关于切片和数组的更多内容,以便理解。

英文:
intput:="This is a string"
output:=[]string{intput}
fmt.Println(intput)
fmt.Println(output)

To understand you should read more about slices and arrays on the Go Blog.

huangapple
  • 本文由 发表于 2017年3月25日 17:12:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/43014592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定