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 get a user home directory path?
+48.3k Golang : Upload file from web browser to server
+9.9k Golang : Check a web page existence with HEAD request example
+40.8k Golang : How to count duplicate items in slice/array?
+11.4k SSL : The certificate is not trusted because no issuer chain was provided
+9.9k Golang : Edge detection with Sobel method
+30.1k Golang : How to redirect to new page with net/http?
+15.1k Golang : Delete certain files in a directory
+8.8k Golang : How to capture return values from goroutines?
+4.3k Javascript : Detect when console is activated and do something about it