當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO EncodeRune用法及代碼示例

GO語言"unicode/utf8"包中"EncodeRune"函數的用法及代碼示例。

用法:

func EncodeRune(p []byte, r rune) int

EncodeRune 將符文的 UTF-8 編碼寫入 p(必須足夠大)。如果符文超出範圍,則寫入RuneError的編碼,返回寫入的字節數。

例子:

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    r := '世'
    buf := make([]byte, 3)

    n := utf8.EncodeRune(buf, r)

    fmt.Println(buf)
    fmt.Println(n)
}

輸出:

[228 184 150]
3

示例(超出範圍):

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    runes := []rune{
        // Less than 0, out of range.
        -1,
        // Greater than 0x10FFFF, out of range.
        0x110000,
        // The Unicode replacement character.
        utf8.RuneError,
    }
    for i, c := range runes {
        buf := make([]byte, 3)
        size := utf8.EncodeRune(buf, c)
        fmt.Printf("%d: %d %[2]s %d\n", i, buf, size)
    }
}

輸出:

0: [239 191 189] � 3
1: [239 191 189] � 3
2: [239 191 189] � 3

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 EncodeRune。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。