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
+6.5k Golang : How to convert strange string to JSON with json.MarshalIndent
+4.4k Golang : How to deal with configuration data?
+9.6k Swift : Convert (cast) String to Integer
+13.6k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+10.7k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+5.2k Golang : Dealing with backquote
+6.9k Javascript : How to check a browser's Do Not Track status?
+9.7k Golang : Create Temporary File
+16.3k Golang : Clone with pointer and modify value
+6.1k Golang : Mapping Iban to Dunging alphabets
+7.4k Golang : Convert word to its plural form example
+39.3k Golang : How to count duplicate items in slice/array?