go 字符串拼接
func main() { s1 := "Hello" + " " + "World" fmt.Println(s1) //Hello World ss := []string{"Hello", "World"} fmt.Println(strings.Join(ss, " ")) //Hello World }
+
可以拼接任意多个字符串。但是+
的缺点是待拼接的字符串必须是已知的。
另一种方式就是使用标准库strings
包中的Join()
函数,这个函数接受一个字符串切片和一个分隔符,将切片中的元素拼接成以分隔符分隔的单个字符串
func ConcatWithMultiPlus() { var s string for i := 0; i < 10; i++ { s += "hello" } } func ConcatWithOnePlus() { s1 := "hello" s2 := "hello" s3 := "hello" s4 := "hello" s5 := "hello" s6 := "hello" s7 := "hello" s8 := "hello" s9 := "hello" s10 := "hello" s := s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10 _ = s } func ConcatWithJoin() { s := []string{"hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello"} _ = strings.Join(s, "") }
三种拼接字符串的方式