split a string into an array of characters in go

To split a string into an array of characters in Go, you can use the strings.Split() function along with a loop to convert each character into a separate string. Here's an example code snippet:

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello world"
    chars := strings.Split(str, "")
    fmt.Println(chars)

    // Alternatively, you can convert each character to its UTF-8 code point:
    codes := []int32(str)
    fmt.Println(codes)
}
278 chars
17 lines

In this code, we use the strings.Split() function to split the str string into a slice of substrings, where each substring is one character. Then, we print the resulting slice.

Alternatively, to convert each character to its UTF-8 code point, we can simply cast the input string to a []int32 slice. This will give us a slice of integer values representing the Unicode code points of each character in the string.

gistlibby LogSnag