OneBite.Dev - Coding blog in a bite size

split a string by a delimiter in Go

Code snippet on how to split a string by a delimiter in Go

  str := "one,two,three"
  delim := ","
  parts := strings.Split(str, delim)

This code uses the strings.Split() function from Go’s inbuilt strings package to split a string by a delimiter. ‘str’ is first assigned a string of “one,two,three”, ‘delim’ is then assigned the delimiter ”,“. Finally, ‘parts’ is assigned the result of the strings.Split() function, which takes ‘str’ and ‘delim’ as parameters. The strings.Split() function will then return an array of the parts of the string that have been split. In this example, the returned array would be [ “one”, “two”, “three” ].

go