strings.go 873 字节
Newer Older
_Fighter's avatar
_Fighter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
package main

import (
	"fmt"
	"unicode/utf8"
)

/*
rune 相当于go的char
使用range遍历 pos ,rune 对
使用utn8.RuneCountInString 获得字符数量
使用len 获得字节长度
使用[]byte 获得字节

*/
func main() {

	s := "love中国!" //UTF-8 一个字占三个字节  ,英文一字节
	fmt.Println(s)
	for _, b := range []byte(s) {
		fmt.Printf("%X ", b)
	}
	fmt.Println()

	// 以下把s 对utf8 进行解码,转换成unicode ,之后赋值给 rune
	for i, ch := range s { // ch is a rune(四字节)
		fmt.Printf(" (%d %X) ", i, ch)
	}
	fmt.Println()

	fmt.Println(" Rune Count:", utf8.RuneCountInString(s))

	bytes := []byte(s)
	for len(bytes) > 0 {
		ch, size := utf8.DecodeRune(bytes)
		bytes = bytes[size:]
		fmt.Printf("%c ", ch)
	}
	fmt.Println()
	for i, ch := range []rune(s) { // ch is a rune(四字节)
		fmt.Printf(" (%d %c) ", i, ch)
	}

}