Trusted answers to developer questions

How to split a string in Golang

The Split() method​ in Golang (defined in the strings library) breaks a string down into a list of substrings using a specified separator. The method returns the substrings in the form of a slice.

Syntax

This is how the function is defined in Golang:

func Split(str, sep string) []string
  • str is the string to be split.
  • The string splits at the specified separator, sep. If an empty string is provided as the separator, then the string is split at every character.
svg viewer

Code

The following code snippet shows how the Split method is used:

package main
import "fmt"
import "strings" // Needed to use Split
func main() {
str := "hi, this is, educative"
split := strings.Split(str, ",")
fmt.Println(split)
fmt.Println("The length of the slice is:", len(split))
}

RELATED TAGS

split
string
golang
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?