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
+17k Golang : Implement getters and setters
+6.8k Android Studio : Rating bar example
+5.3k Golang : Break string into a slice of characters example
+5.8k Golang : Get expvar(export variables) to work with multiplexer
+14.1k Golang : Validate hostname
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+6.3k Golang : alternative to os.Exit() function
+16k Golang : Defer function inside init()
+7.4k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+6.1k Golang : Array mapping with Interface
+10.7k Golang : Perform sanity checks on filename example
+26.5k Get file path of temporary file in Go