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
+10.1k Golang : Convert octal value to string to deal with leading zero problem
+5.8k Golang : Struct field tags and what is their purpose?
+11.2k Golang : Read until certain character to break for loop
+8k Javascript : Put image into Chrome browser's console
+5.2k Linux : How to set root password in Linux Mint
+5.1k Python : Convert(cast) bytes to string example
+4.8k Chrome : How to block socketloop.com links in Google SERP?
+18.1k Golang : Login and logout a user after password verification and redirect example
+3.7k Java : Get FX sentiment from website example
+9k Golang : Find network service name from given port and protocol
+17.6k Golang : Multi threading or run two processes or more example