AppDividend
Latest Code Tutorials

How To Join Strings In Golang | Go String Join() Example

0

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.

How To Join Strings In Golang

Golang Join() method combines the slice of strings into a single string. We pass it the slice as a first argument. The delimiter 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

See also

Golang String Fields()

How To Sort Slice In Golang

How to compare two slices in Golang

Golang String Contains()

Golang String make()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.