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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.