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
+16.6k Golang : Simple client server example
+20.2k Golang : Convert(cast) string to rune and back to string example
+5.2k PageSpeed : Clear or flush cache on web server
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+15k Golang : Get file permission
+19.3k PHP : Convert(cast) int to double/float
+3.7k Linux/MacOSX : Search and delete files by extension
+11.7k Golang : Pass database connection to function called from another package and HTTP Handler
+5.3k Golang : Join lines with certain suffix symbol example
+6.4k Golang : Not able to grep log.Println() output
+29.3k Golang : How to redirect to new page with net/http?
+7.9k Golang : Take screen shot of browser with JQuery example