In this shot, we’ll learn how to join a slice into a string using a separator in Golang.
We can use the Join
function from the strings
package to join a slice.
strings.Join(slice, separator)
The Join
function accepts two parameters:
slice
: The elements that need to be converted to a string.separator
: We can join a slice with separators like a space, underscore, hyphen, etc.Join
returns a new string with all the elements present in the slice.
In this example, we will try to join a slice of strings into a string with _
as a separator.
package main//import format and strings packageimport("fmt""strings")//program executin starts herefunc main(){//Declare a slices := []string{"This","is","an","example"}//Join slice into a stringsnew := strings.Join(s,"_")//display the stringfmt.Println(snew)}
In the code snippet above:
Lines 5 and 6: We import the format
and strings
packages.
Line 10: The program execution starts from the main()
function in Golang.
Line 13: We declare and initialize the slice s
, which is a collection of strings.
Line 16: We use the Join()
function to join the slice with the _
separator.
Line 19: We display the string that is created from joining the slice.