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
+12.9k Golang : How to determine if user agent is a mobile device example
+9.2k Generate Random number with math/rand in Go
+10.4k Swift : Convert (cast) Float to String
+4.5k Clean up Visual Studio For Mac installation failed disk full problem
+14.1k Golang : Get current time from the Internet time server(ntp) example
+4.1k Golang : Constant and variable names in native language
+24.4k Golang : Get executable name behind process ID example
+18.5k Golang : Append content to a file
+15.9k Golang : Defer function inside init()
+4.5k Golang : Get S3 or CloudFront object or file information
+6.7k Golang : Get today's weekday name and calculate target day distance example