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
+9.9k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+48.7k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+14.9k Golang : convert string or integer to big.Int type
+18.5k Golang : Append content to a file
+14.8k Golang : Get sub string example
+36.5k Golang : Comparing date or timestamp
+28k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+8.5k Golang : interface - when and where to use examples
+17.8k Golang : Get RGBA values of each image pixel
+28k Golang : Get time.Duration in year, month, week or day
+9.1k Golang : Get login name from environment and prompt for password
+6.5k Golang : Shuffle strings array