Go五种字符串的拼接

+

func main() {
    s1 := "hello"
    s2 := "word"
    s3 := s1 + s2
    fmt.Print(s3) //s3 = "helloword"
}

sprintf

s1 := "hello"
s2 := "word"
s3 := fmt.Sprintf("%s%s", s1, s2) //s3 = "helloword"

Join

s1 := "hello"
s2 := "word"
var str []string = []string{s1, s2}
s3 := strings.Join(str, "")
fmt.Print(s3) //s3 = "helloword"

bytes.Buffer

s1 := "hello"
s2 := "word"
var bt bytes.Buffer
bt.WriteString(s1)
bt.WriteString(s2)
s3 := bt.String()
fmt.Println(s3)//s3 = "helloword"

strings.Builder

s1 := "hello"
s2 := "word"
var build strings.Builder
build.WriteString(s1)
build.WriteString(s2)
s3 := build.String()
fmt.Println(s3)//s3 = "helloword"

一般情况下我都是用+拼接,如果拼接的字符串比较长的话就是最后一种方式了

posted @ 2024-09-28 11:40  朝阳1  阅读(4)  评论(0编辑  收藏  举报