How to concatenate strings in golang?
In this article, you are going to learn about string concatenation in Golang.
String concatenation means the way of adding two or more strings into a new single string. Like other programming languages, Golang has the functionality of string concatenation. In Go language, the string is a read-only slice of bytes that is also known as an immutable arbitrary chain.
String concatenation means the way of adding two or more strings into a new single string. Like other programming languages, golang has the functionality of string concatenation. In Go language, the string is a read-only slice of bytes that is also known as an immutable arbitrary chain.
package main
import "fmt"
func main() {
var str1 string
str1 = "Hello"
var str2 string
str2 = "World!"
fmt.Println("New concatenate string: ", str1+str2)
}
// Output: New concatenate string: HelloWorld!
You can concatenate two strings by using + operator. Now your task is to create a space between helloWorld! and show it as “Hello World!” as output.
Apart from + operator there are other ways of concatenating strings in Go language. Let’s explore them.
bytes.Buffer
Golang lets you concatenate two or more string by using bytes.Buffer. To perform this action, all you need to do is import bytes package and use it with the help of WriteString() method. See the below code example :
package main
import (
"bytes"
"fmt"
)
func main() {
var x bytes.Buffer
x.WriteString("H")
x.WriteString("e")
x.WriteString("l")
x.WriteString("l")
x.WriteString("o")
fmt.Println("Output: ", x.String())
x.WriteString(" ")
x.WriteString("W")
x.WriteString("o")
x.WriteString("r")
x.WriteString("l")
x.WriteString("d")
x.WriteString("!")
fmt.Println("Output: ", x.String())
}
//Output :
// Output : Hello
// Output : Hello World!
Sprintf:
Using Sprintf() method is another way of concatenating strings in Go language. Example:
package main
import "fmt"
func main() {
str1 := "Hello"
str2 := " "
str3 := "World!"
result := fmt.Sprintf("%s%s%s", str1,
str2, str3)
fmt.Println(result)
}
//Output : Hello World!
Join() function:
This function concatenates all the elements present in the slice of string into a single string. Example:
package main
import (
"fmt"
"strings"
)
func main() {
testslice := []string{"Hello", "World!"}
result := strings.Join(testslice, " ")
fmt.Println(result)
}
//Output : Hello World!
Here, in the testslice we take multiple words and concatenate them with the help of Join() method and separate those words with an empty space.
+= operator:
Using += operator is another way of concatenating strings in Go language. Example:
package main
import "fmt"
func main() {
str1 := "Hello "
str2 := "World!"
str1 += str2
fmt.Println(str1)
}
//Output: Hello World!
Here, += operator adds str2 string to the end of the str1 string and shown “Hello World!” as output.
This is all about concatenating strings in go language and you will get an overview about string concatenation in golang from this article.