← 中文资源

简体中文版本

用 DecodeRuneInString 区分真实 U+FFFD 与坏字节

调用 utf8.DecodeRuneInString 按字符串偏移逐步扫描,将宽度为 1 的非法字节与宽度为 3 的合法替换字符 U+FFFD 明确区分开。

阅读英文原文

实现说明

逻辑集中在函数 inspectUTF8、main里。 在这里做循环的是 for i := 0; i < len(s);。

使用要点

  • 仅有原生语言运行时一项要求——无外部包,无额外安装。
  • 每一步打印都带着自己的标签:input valid=、offset。
  • main 的演示流程是 inspectUTF8——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「用 DecodeRuneInString 区分真实 U+FFFD 与坏字节」会打印什么?

运行文件本身,input valid=、offset 这些前缀各对应一段演示逻辑。

签名一览:func inspectUTF8(s string)

核心语句

func main() {
	// Contains genuine U+FFFD (3 bytes: ef bf bd) plus invalid raw byte 0xff
	sample := "ok-\ufffd-\xff!"
	inspectUTF8(sample)
}

代码示例

package main

import (
	"fmt"
	"unicode/utf8"
)

func inspectUTF8(s string) {
	fmt.Printf("input valid=%t bytes=%x\n", utf8.ValidString(s), s)
	for i := 0; i < len(s); {
		r, width := utf8.DecodeRuneInString(s[i:])
		if r == utf8.RuneError && width == 1 {
			fmt.Printf("  offset %d: invalid byte 0x%02x (width=1)\n", i, s[i])
		} else {
			fmt.Printf("  offset %d: rune %q U+%04X (width=%d)\n", i, r, r, width)
		}
		i += width
	}
}

func main() {
	// Contains genuine U+FFFD (3 bytes: ef bf bd) plus invalid raw byte 0xff
	sample := "ok-\ufffd-\xff!"
	inspectUTF8(sample)
}