pet*_*rSO 5

在 Go 中,字符文字作为 UTF-8 编码字节的可变宽度序列存储在字符串中。ASCII 代码点 (0x00..0x7F) 占用 1 个字节。其他代码点占用两到四个字节。要单独打印代码点(字符),

package main

import "fmt"

func main() {
    strslice := make([]string, 5, 5)
    strslice[0] = "hello"
    strslice[1] = "go"
    strslice[2] = "lang"
    strslice[3] = "whatsup"
    strslice[4] = "Hello, ??"
    for _, s := range strslice {
        for _, c := range s {
            fmt.Printf("%c ", c)
        }
        fmt.Printf("\n")
    }
}

输出:

h e l l o 
g o 
l a n g 
w h a t s u p 
H e l l o ,   ? ? 

这是 UTF-8 编码字节和字符之间差异的说明,

package main

import "fmt"

func main() {
    str := "Hello, ??"
    fmt.Println("Bytes:")
    for i := 0; i < len(str); i++ {
        fmt.Printf("'%c' ", str[i])
    }
    fmt.Printf("\n")
    fmt.Println("Characters:")
    for _, c := range str {
        fmt.Printf("'%c' ", c)
    }
    fmt.Printf("\n")
}

输出:

Bytes:
'H' 'e' 'l' 'l' 'o' ',' ' ' 'ä' '¸' '' 'ç' '' '' 
Characters:
'H' 'e' 'l' 'l' 'o' ',' ' ' '?' '?' 

参考: