如何在 Golang 中连接两个字符串?
在 Golang 中连接两个字符串的最简单方法是使用“+”运算符。例如,
示例 1
package main输出结果import (
"fmt"
)
func main() {
str1 := "Hello..."
str2 := "How are you doing?"
fmt.Println("第一个字符串:", str1)
fmt.Println("第二个字符串:", str2)
//使用 + 运算符连接
fmt.Println("串联字符串:", str1 + str2)
}
它将产生以下输出
第一个字符串: Hello...第二个字符串: How are you doing?
串联字符串: Hello...How are you doing?
连接使用strings.Join()
strings.Join()是 Golang 中的内置函数,用于将字符串切片连接成单个字符串。
语法
它的语法如下 -
func Join(stringSlice []string, sep string) string
在哪里,
stringSlice – 要连接的字符串。
sep – 它是一个分隔字符串,将放置在切片元素之间。
示例 2
让我们考虑以下示例 -
package main输出结果import (
"fmt"
"strings"
)
func main() {
//初始化字符串
m := []string{"IndexByte", "String", "Function"}
n := []string{"Golang", "IndexByte", "String", "Package"}
//显示字符串
fmt.Println("Set 1 - Slices of Strings:", m)
fmt.Println("Set 2 - Slices of Strings:", n)
//使用连接功能
output1 := strings.Join(m, "-")
output2 := strings.Join(m, "/")
output3 := strings.Join(n, "*")
output4 := strings.Join(n, "$")
//显示连接输出
fmt.Println("\n Joining the slices of Set 1 with '-' delimiter: \n", output1)
fmt.Println("\n Joining the slices of Set 1 with '/' delimiter: \n", output2)
fmt.Println("\n Joining the slices of Set 2 with '*' delimiter: \n", output3)
fmt.Println("\n Joining the slices of Set 2 with '$' delimiter: \n", output4)
}
它将生成以下输出 -
Set 1 - Slices of Strings: [IndexByte String Function]Set 2 - Slices of Strings: [Golang IndexByte String Package]
Joining the slices of Set 1 with '-' delimiter:
IndexByte-String-Function
Joining the slices of Set 1 with '/' delimiter:
IndexByte/String/Function
Joining the slices of Set 2 with '*' delimiter:
Golang*IndexByte*String*Package
Joining the slices of Set 2 with '$' delimiter:
Golang$IndexByte$String$Package
示例 3
让我们再举一个例子。
package main输出结果import (
"fmt"
"strings"
)
func main() {
//定义变量
var s []string
var substr string
var substr1 string
var result string
var output string
//初始化字符串
s = []string{"This", "is", "String", "Function"}
substr = "..."
substr1 = " "
//显示字符串的输入切片
fmt.Println("输入字符串切片:", s)
//使用连接功能
result = strings.Join(s, substr)
output = strings.Join(s, substr1)
//显示 Join 函数的输出
fmt.Println("Joining with '...' delimiter:", result)
fmt.Println("Joining with ' ' delimiter:", output)
}
它将生成以下输出 -
输入字符串切片: [This is String Function]Joining with '...' delimiter: This...is...String...Function
Joining with ' ' delimiter: This is String Function
以上是 如何在 Golang 中连接两个字符串? 的全部内容, 来源链接: utcz.com/z/297371.html