如何将字符串切片连接成一个字符串?

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

How to join a slice of strings into a single string?

问题

以下是翻译好的内容:

package main

import (
	"fmt"
	"strings"
)

func main() {
	reg := [...]string {"a","b","c"}
	fmt.Println(strings.Join(reg,","))
}

给我一个错误:

prog.go:10: 无法将 reg (类型 [3]string) 作为参数传递给 strings.Join 的类型 []string

是否有比循环和添加到变量更直接/更好的方法?

英文:
package main

import (
"fmt"
"strings"
)

func main() {
reg := [...]string {"a","b","c"}
fmt.Println(strings.Join(reg,","))
}

gives me an error of:
>prog.go:10: cannot use reg (type [3]string) as type []string in argument to strings.Join

Is there a more direct/better way than looping and adding to a var?

答案1

得分: 257

你的问题标题是:

如何将字符串切片连接成一个字符串?

但实际上,reg 不是一个切片,而是一个长度为三的数组。[...]string 只是语法糖,表示(在这种情况下)[3]string

要获取一个真正的切片,你应该这样写:

reg := []string {"a","b","c"}

(在这里尝试一下:https://play.golang.org/p/vqU5VtDilJ。)

顺便说一下,如果你确实需要将字符串数组连接成一个字符串,你可以通过添加 [:] 来从数组中获取一个切片,像这样:

fmt.Println(strings.Join(reg[:], ","))

(在这里尝试一下:https://play.golang.org/p/zy8KyC8OTuJ。)

英文:

The title of your question is:

> How to join a slice of strings into a single string?

but in fact, reg is not a slice, but a length-three array. [...]string is just syntactic sugar for (in this case) [3]string.

To get an actual slice, you should write:

reg := []string {"a","b","c"}

(Try it out: https://play.golang.org/p/vqU5VtDilJ.)

Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:], like so:

fmt.Println(strings.Join(reg[:], ","))

(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)

答案2

得分: 127

使用切片而不是数组。只需使用以下代码创建切片:

reg := []string{"a", "b", "c"}

另一种方法是在连接时将数组转换为切片:

fmt.Println(strings.Join(reg[:], ","))

阅读Go博客关于切片和数组之间的区别

英文:

Use a slice, not an arrray. Just create it using

reg := []string {"a","b","c"}

An alternative would have been to convert your array to a slice when joining :

fmt.Println(strings.Join(reg[:],","))

Read the Go blog about the differences between slices and arrays.

答案3

得分: 44

这在2018年仍然相关。

转换为字符串

import strings
stringFiles := strings.Join(fileSlice[:], ",")

再次转换为切片

import strings
fileSlice := strings.Split(stringFiles, ",")
英文:

This is still relevant in 2018.

To String

import strings
stringFiles := strings.Join(fileSlice[:], ",")

Back to Slice again

import strings
fileSlice := strings.Split(stringFiles, ",")

huangapple
  • 本文由 发表于 2015年3月2日 05:09:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/28799110.html
匿名

发表评论

匿名网友

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

确定