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
+19.9k nginx: [emerg] unknown directive "passenger_enabled"
+14.8k Golang : Get all local users and print out their home directory, description and group id
+13.2k Golang : Set image canvas or background to transparent
+5.8k Javascript : Get operating system and browser information
+11.6k Golang : How to parse plain email text and process email header?
+10.9k Golang : How to use if, eq and print properly in html template
+27.7k Golang : Connect to database (MySQL/MariaDB) server
+10.8k Golang : Intercept and process UNIX signals example
+26.2k Golang : Encrypt and decrypt data with AES crypto
+21.2k Golang : Convert string slice to struct and access with reflect example
+7.6k Golang : Check from web if Go application is running or not
+25.4k Golang : How to read integer value from standard input ?