gpt4 book ai didi

string - 为什么 utf-8 编码的 byte\xbd 在 for range 循环中被格式化为 unicode 代码点 fffd?

转载 作者:行者123 更新时间:2023-12-03 01:26:27 25 4
gpt4 key购买 nike

这是 Go blog 中的练习。
[练习:将无效的 UTF-8 字节序列放入字符串中。 (如何?)循环的迭代会发生什么?]

我所做的是

    const nihongo = "\xbd日本語\xbd"
for index, runeValue := range nihongo {
fmt.Printf("%x, %d\n", runeValue, index)
}

输出是

fffd, 0
65e5, 1
672c, 4
8a9e, 7
fffd, 10

我的问题是。 utf-8编码字节bd如何格式化为单位代码点u+fffd

最佳答案

此行为由 Spec: For statements: 指定

For statements with range clause

For a string value, the "range" clause iterates over the Unicode code points in the string starting at byte index 0. On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string, and the second value, of type rune, will be the value of the corresponding code point. If the iteration encounters an invalid UTF-8 sequence, the second value will be 0xFFFD, the Unicode replacement character, and the next iteration will advance a single byte in the string.

关于string - 为什么 utf-8 编码的 byte\xbd 在 for range 循环中被格式化为 unicode 代码点 fffd?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58992819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com