Golang String Join() is an inbuilt function that concatenates the items of its first argument to create the single string. The separator string is placed between items in the resulting String—the strings.Join() method is used to merge a string slice with a delimiter in between each String.
Golang join()
Golang Join() is a built-in String method that combines the slice of strings into a single string. We pass it the slice as a first argument. The delimiter is to be inserted in the second.
Syntax
func Join(elems []string, seperator string) string
Parameter
With the Join() function, we must pass two arguments. To join with no delimiter (convert the string slice to a string), we can use an empty string as the delimiter.
Example
// hello.go package main import ( "fmt" "strings" ) func main() { OTT := []string{"Quibi", "Disney+", "Netflix"} fmt.Println(strings.Join(OTT, ", ")) }
Output
go run hello.go Quibi, Disney+, Netflix
In the above code, we have joined three strings using a semicolon. (,)
Use other delimiters to join strings
// hello.go package main import ( "fmt" "strings" ) func main() { OTT := []string{"Quibi", "Disney+", "Netflix"} fmt.Println(strings.Join(OTT, "...")) }
Output
go run hello.go Quibi...Disney+...Netflix
No delimiter
Suppose we have the slice of strings, and each String is the same length.
We can join these strings together and then extract them based on their length alone. To achieve that, No delimiter is needed.
We can join with an empty string. It creates the most compact string representation possible.
// hello.go package main import ( "fmt" "strings" ) func main() { // A slice of three strings. values := []string{"Krunal", "Devendrabhai", "Lathiya"} // Join with no separator to create a compact string joined := strings.Join(values, "") fmt.Println(joined) }
Output
go run hello.go KrunalDevendrabhaiLathiya
When we join a slice together, we some information about the individual strings. Data loss can occur if we have a delimiter inside one of the strings. This is something we have to look for.
Using the + operator to join strings in Golang
See the following code.
// hello.go package main import ( "fmt" ) func main() { str1 := "John" // there is a space before World str2 := " Krasinski" fmt.Println(str1 + str2) }
Output
go run hello.go John Krasinski