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
+23.1k Golang : Print out struct values in string format
+12.5k Golang : flag provided but not defined error
+5.8k Golang : Find change in a combination of coins example
+13.4k Golang : Verify token from Google Authenticator App
+12.3k Golang : Display list of countries and ISO codes
+8.9k Golang : Gaussian blur on image and camera video feed examples
+13.5k Golang : Count number of runes in string
+14k Golang : Reverse IP address for reverse DNS lookup example
+10.9k Golang : Create Temporary File
+7.8k Golang : Reverse a string with unicode
+24.5k Golang : Time slice or date sort and reverse sort example
+5.4k Unix/Linux : How to archive and compress entire directory ?