How to iterate over string characters in Go
To iterate over the characters in a string, a for..range loop may be utilised.
package main
import "fmt"
func main() {
str := "I ♥ Go!"
for _, ch := range str {
fmt.Println(ch)
}
}Run this example on the Go playground
This outputs the Unicode code point for each character in the string:
73
32
9829
32
71
111
33If you need to access the characters represented by the Unicode code point, you
can use the %c fmt verb with fmt.Printf or fmt.Sprintf:
package main
import "fmt"
func main() {
str := "I ♥ Go!"
for _, ch := range str {
fmt.Printf("%c\n", ch)
}
}Run this example on the Go playground
I
♥
G
o
!Thanks for reading, and happy coding!