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.8k Golang : Capture stdout of a child process and act according to the result
+18.2k Golang : How to get hour, minute, second from time?
+4.6k PHP : Extract part of a string starting from the middle
+42.9k Golang : Get hardware information such as disk, memory and CPU usage
+13.7k Golang : Get current time
+6k Golang : Process non-XML/JSON formatted ASCII text file example
+9.3k Facebook : Getting the friends list with PHP return JSON format
+32k Golang : Convert []string to []byte examples
+6.9k Golang : Get Alexa ranking data example
+7.5k Golang : get the current working directory of a running program
+7k Golang : Transform lisp or spinal case to Pascal case example
+7.1k Golang : Accessing dataframe-go element by row, column and name example