Utf8 Rune Counting And Byte Indices

Range over strings knowing indexes are byte offsets, count runes instead of bytes, and cut safely with ValidString guarding mid-rune slices.

GoData Integrity

Code

gosnippet
22 lines
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	// range 按字节偏移给出下标,rune 才是字符本身
	slogan := "héllo 世界"
	for i, r := range slogan {
		fmt.Printf("byte %d -> %q\n", i, r)
	}

	// 字符数用 RuneCountInString,而不是 len
	fmt.Println("bytes:", len(slogan), "runes:", utf8.RuneCountInString(slogan))

	// 切到 rune 边界内会产生非法字节,用 ValidString 检出
	fmt.Println("safe cut:", slogan[:6], "valid:", utf8.ValidString(slogan[:6]))
	broken := slogan[:2]
	fmt.Printf("mid-rune cut: %q, valid=%t\n", broken, utf8.ValidString(broken))
}

How it works

Utf8 Rune Counting And Byte Indices is built around the function main.

for i, r := range slogan is the loop that carries the per-item work.

Using it

Running the file prints labeled results such as byte, bytes:, safe cut: — each operation’s effect is visible in the output.

Key statements

for i, r := range slogan {
fmt.Printf("byte %d -> %q\n", i, r)
}

Interactive Tools for This Topic

FAQ

What does Utf8 Rune Counting And Byte Indices print when run?
Execute the whole file; each printed line is prefixed with a label like `byte`, `bytes:`, `safe cut:`.