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
+7.7k Golang : Check from web if Go application is running or not
+13.9k Golang : Check if a file exist or not
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+18.6k Golang : Padding data for encryption and un-padding data for decryption
+11.2k Golang : Generate DSA private, public key and PEM files example
+13.5k Golang : Convert spaces to tabs and back to spaces example
+12k Golang : flag provided but not defined error
+37.4k Golang : Comparing date or timestamp
+21.8k Golang : Securing password with salt
+7.6k Setting $GOPATH environment variable for Unix/Linux and Windows
+12k Golang : calculate elapsed run time
+29.5k Golang : Get and Set User-Agent examples