In Golang, you can access individual characters in a string by treating the string as a read-only byte slice. Here's an example:
package main
import "fmt"
func main() {
str := "Hello, World!"
for i := 0; i < len(str); i++ {
fmt.Printf("Character at index %d is %c\n", i, str[i])
}
}
Output:
Character at index 0 is H
Character at index 1 is e
Character at index 2 is l
Character at index 3 is l
Character at index 4 is o
Character at index 5 is ,
Character at index 6 is
Character at index 7 is
Character at index 8 is W
Character at index 9 is o
Character at index 10 is r
Character at index 11 is l
Character at index 12 is d
Character at index 13 is !
In this example, we use a for loop to iterate over each character in the string. We access the character at a specific index by using str[i]
, where i
is the index. The %c
format verb is used to print the character.