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
+14.3k Golang : Chunk split or divide a string into smaller chunk example
+10.5k Generate Random number with math/rand in Go
+41.4k Golang : How to count duplicate items in slice/array?
+6.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+12.4k Golang : Get month name from date example
+5.4k Golang : How to deal with configuration data?
+16.5k Golang : Send email and SMTP configuration example
+6.8k Golang : Derive cryptographic key from passwords with Argon2
+9.6k Golang : Convert(cast) string to int64
+14.8k Golang : Reset buffer example
+32.8k Golang : Regular Expression for alphanumeric and underscore
+8.8k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared