Home
Go
Join Examples (strings.Join)
This page was last reviewed on Oct 16, 2021.
Dot Net Perls
Join. This Golang method combines a slice of strings into a single string. We pass it the slice as the first argument. The delimiter to be inserted is the second.
Slice
With join we must pass 2 arguments. To join with no delimiter (convert a string slice to a string) we can use an empty string as the delimiter. This works well.
strings.Split
First example. Here we create an empty string slice and then append 3 strings. We join those strings together with ellipses. The Join() func in Go is like those in many other languages.
package main import ( "fmt" "strings" ) func main() { // Create a slice and append three strings to it. values := []string{} values = append(values, "cat") values = append(values, "dog") values = append(values, "bird") // Join three strings into one. result := strings.Join(values, "...") fmt.Println(result) }
cat...dog...bird
No delimiter. Suppose we have a 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.
Detail No delimiter is needed. We can join with an empty string. This creates the most compact string representation possible.
package main import ( "fmt" "strings" ) func main() { // A slice of 3 strings. values := []string{"a", "b", "c"} // Join with no separator to create a compact string. joined := strings.Join(values, "") fmt.Println(joined) }
abc
A review. 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 must be tested for.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 16, 2021 (image).
Home
Changes
© 2007-2024 Sam Allen.