len, strings.Index, strings.IndexRune
func Index(s, substr string) int
func IndexRune(s string, r rune) intReport the byte offset of a substring or rune. Combine this with len and utf8.RuneCountInString to see why a string can have more bytes than characters.
| Parameter | Description |
|---|---|
s | The string to search, treated as a sequence of bytes. |
substr / r | The substring or rune to find. IndexRune cannot search for a multi-rune string; use Index for that. |
Returns: The byte index of the first match, or -1 if there is no match. These functions do not return a rune index.
- In "Go语言", "Go" is two bytes and each of the next two runes is three bytes, so len is 8 and the rune count is 4.
- Both Index(s, "语") and IndexRune(s, '语') return 2, which is a byte offset, not "the third character" counted from one.
- s[0:2] is safe here because it lands on a rune boundary. s[0:3] would cut inside 语.
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
s := "Go语言"
fmt.Println(len(s), utf8.RuneCountInString(s))
fmt.Println(strings.Index(s, "语"), strings.IndexRune(s, '语'))
fmt.Println(s[0:2], string([]rune(s)[0:3]))
}Expected output
8 4
2 2
Go Go语Related: unicode/utf8.RuneCountInString