Golang : Convert string to array/slice

Just a note for my own self. Hope it will be useful for you.

Problem :

You have a string like this :

apple orange durian pear

and you want to convert this string into an array

Solution :

Use strings.Fields() function to instantly convert the string into an array.

 package main

 import (

 func main() {
  str := "apple orange durian pear"

  strArray := strings.Fields(str)


Output :

[apple orange durian pear]

[orange durian]

Reference :


By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.