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
+16.3k Golang : Find out mime type from bytes in buffer
+17.6k Convert JSON to CSV in Golang
+32.9k Golang : How to check if a date is within certain range?
+6.8k How to let Facebook Login button redirect to a particular URL ?
+13.4k Golang : How to get year, month and day?
+6.7k Golang : Output or print out JSON stream/encoded data
+13.8k Golang : convert(cast) string to float value
+12.2k Golang : List running EC2 instances and descriptions
+14.3k Golang : How to shuffle elements in array or slice?
+6.9k Golang : How to call function inside template with template.FuncMap
+22.1k Golang : Securing password with salt