OneBite.Dev - Coding blog in a bite size

convert a string to an array in Go

Code snippet on how to convert a string to an array in Go

  words := strings.Fields(str)

This code snippet uses the Fields() function of Go’s strings package to convert a string to an array. This takes a string as an argument and returns a string slice—an array of strings—which can be assigned to the words variable. Every element in the array is a string composed of characters separated by whitespace characters from the original string passed as argument. For instance, if the string “Hello World” is passed as an argument, the output of the slice or array will be [“Hello”, “World”]. This code is useful when working with strings in the Go programming language to convert long strings into manageable data structures.

go