Skip to content

How to Split a String Into a Slice and Join Them Back [Golang]

If you want to work with a piece of string in Golang then your best friend is strings package!

The split function can convert a string into a separated slice of string:

func strings.Split(s string, separator string) []string
package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "My name is Morteza!"

	words := strings.Split(str, " ")

	for _, word := range words {
		fmt.Println(word)
	}
}

And join function can concatenate a slice of string into one:

func strings.Join(elems []string, separator string) string
package main

import (
	"fmt"
	"strings"
)

func main() {
	parts := []string{"https://www.code-paste.com", "path", "to", "post"}

	url := strings.Join(parts, "/")

	fmt.Println("url:", url)
}

Leave a Reply

Your email address will not be published. Required fields are marked *