Home > Backend Development > Golang > How to concatenate strings in golang

How to concatenate strings in golang

(*-*)浩
Release: 2019-12-31 11:55:22
Original
2256 people have browsed it

How to concatenate strings in golang

There are many methods of string splicing supported in the go language. Here is a list

Commonly used string splicing methods

1. The most common method is definitely to concatenate two strings. (Recommended Learning: Go )

## This is similar to Python, but because the string in Golang is an indispensable type, a new character string pair with a connection will generate a connection. Efficiency has an impact.

s1 := "字符串"
s2 := "拼接"
s3 := s1 + s2
fmt.Print(s3) //s3 = "打印字符串"
Copy after login

2. The second method uses the sprintf function, although it will not generate a temporary string like using it directly. But the efficiency is not high

s1 := "字符串"
s2 := "拼接"
s3 := fmt.Sprintf("%s%s", s1, s2) //s3 = "打印字符串"
Copy after login

3. The third method is to use the Join function. Here we need to introduce the strings package before calling the Join function.

The Join function will first calculate the length after splicing based on the contents of the string array, then apply for memory of the corresponding size and fill in the strings one by one. If there is already an array , this efficiency will be very high, otherwise it will not be efficient.

//需要先导入strings包
s1 := "字符串"
s2 := "拼接"
//定义一个字符串数组包含上述的字符串
var str []string = []string{s1, s2}
//调用Join函数
s3 := strings.Join(str, "")
fmt.Print(s3)
Copy after login

The above is the detailed content of How to concatenate strings in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template