Convert String into Array of Characters
To convert a string into array of characters (which is slice of runes) in Go language, pass the string as argument to []rune(). This will create a slice of runes where each character is stored as an element in the resulting slice.
We do not know how many characters would be there in a string, so converting given string into a slice is better option than converting to an actual array type in Go, where array is of fixed size. Also, each character is a unicode point which can be stored as a rune. Therefore array of characters mean slice of runes, at least for this tutorial.
Example
In the following example, we take a string in str
, and convert it to slice of characters.
Example.go
package main
func main() {
str := "ab£"
chars := []rune(str)
for i := 0; i < len(chars); i++ {
char := string(chars[i])
println(char)
}
}
Inside the loop, we converted rune value to string using string() function.
Output
a
b
£
Conclusion
In this Golang Tutorial, we learned how to convert a string into an array of characters in Go language, with example program.