How to Index Characters in a String in Go
Created
Modified
Using individual characters
In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. For example,
package main
import "fmt"
func main() {
s := "Hello,世界"
fmt.Println(string(s[1]))
fmt.Println(string([]rune(s)[6]))
}
e 世
Using strings.Split Function
Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.
See the following example:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello,世界"
b := strings.Split(s, "")
fmt.Println(b[6])
}
世
Golang Errors
panic: runtime error: index out of range [9] with length 8:
fmt.Println(b[9])
panic: runtime error: index out of range [9] with length 8 goroutine 1 [running]: