Midonya

How to Convert String to Slice of Characters in Go

How to Convert String to Slice of Characters in Go

 In this article, I’ll share with you a few ways to break a string into characters in Go:

  1. Using strings.Split()
  2. Using rune() – this is my preferred approach
  3. Using byte()

1. Break String into Character Substrings using strings.Split()

Given a string and a delimiter, strings.Split() slices the string into a slice of substrings.

When the delimiter is empty, the function returns a slice of the individual Unicode characters that make up the string instead.

[Example]

str := "Hello World"
res := strings.Split(str, "")

fmt.Printf("Data type: %T\n", res[0])
fmt.Printf("Characters: %q\n", res)

Note: Package strings need to be imported.

[Output]

Data type: string
Characters: ["H" "e" "l" "l" "o" " " "W" "o" "r" "l" "d"]

This approach is helpful when you want the result to be a slice of strings.