1. Home
  2. Docs
  3. golang
  4. 内置库(包-package)
  5. utf8

utf8

utf8.DecodeRune

DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and its width in bytes. If p is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it returns (RuneError, 1). Both are impossible results for correct, non-empty UTF-8.

An encoding is invalid if it is incorrect UTF-8, encodes a rune that is out of range, or is not the shortest possible UTF-8 encoding for the value. No other validation is performed.

DecodeRune解开p中的第一个UTF-8编码,并返回符文和它的宽度(字节)。如果p是空的,它返回(RuneError, 0)。否则,如果编码无效,它返回(RuneError, 1)。对于正确的、非空的UTF-8来说,这两种结果都是不可能的。

如果一个编码是不正确的UTF-8,编码的符文超出了范围,或者不是最短的UTF-8编码的值,那么这个编码就是无效的。不进行其他验证。

    b := []byte("Hello, 世界")

    for len(b) > 0 {
        r, size := utf8.DecodeRune(b)
        fmt.Printf("%c %v\n", r, size)

        b = b[size:]
    }
输出
H 1
e 1
l 1
l 1
o 1
, 1
  1
世 3
界 3
Was this article helpful to you? Yes No

How can we help?