split a string into an array of substrings in go

To split a string into an array of substrings in Go, we can use the strings package and the Split function. The Split function takes two arguments: the string to be split and a separator which defines where to split the string. It returns a slice of strings.

Here's an example code snippet to split a string into an array of substrings based on whitespace:

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello World! This is a sample string."
    
    // split string using whitespace separator
    arr := strings.Split(str, " ")

    // print array of substrings
    fmt.Println(arr)
}
259 chars
17 lines

This will output:

main.go
[Hello World! This is a sample string.]
40 chars
2 lines

We can also split a string based on a different separator, such as a comma, by changing the separator argument in the Split function. For example:

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "apple,banana,orange"
    
    // split string using comma separator
    arr := strings.Split(str, ",")

    // print array of substrings
    fmt.Println(arr)
}
236 chars
17 lines

This will output:

main.go
[apple banana orange]
22 chars
2 lines

gistlibby LogSnag