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 (
"fmt"
"strings"
)
func main() {
str := "apple orange durian pear"
strArray := strings.Fields(str)
fmt.Println(strArray)
fmt.Println(strArray[1:3])
}
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.
Advertisement
Tutorials
+21.1k Golang : Sort and reverse sort a slice of strings
+5.7k Golang : Frobnicate or tweaking a string example
+8k Javascript : Put image into Chrome browser's console
+17.4k Golang : How to tell if a file is compressed either gzip or zip ?
+8k Golang : Ways to recover memory during run time.
+7.6k Golang : How to stop user from directly running an executable file?
+11.5k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+21.1k Golang : For loop continue,break and range
+32.2k Golang : Convert []string to []byte examples
+17k Golang : How to generate QR codes?
+6.6k Golang : Map within a map example