go内建容器-字符和字符串操作

1.基础定义

在基础语法篇提到过golang的rune相当于其他编程语言的char,其本质是一个int32(四字节),用[]rune来转换一个字符串时,得到的是个解码后的结果,存储在新开辟的[]rune空间中,而不是对原字符串进行'解释'

对[]byte进行解码需要用到utf8包中的DecodeRune(p []byte) (r rune, size int)函数

2.常用包

在进行字符和字符串操作时常用的包有unicode/utf8(解码、转码等功能)和strings(字符串操作),两个包里的函数很多,不一一展示

测试代码

package main
import (
	"fmt"
	"strings"
	"unicode/utf8"
)
func testChars()  {
	s :="golang真好玩!" //UTF-8
	fmt.Println("utf8")
	for _,b := range []byte(s){
		fmt.Printf("%X ",b)
	}
	strings.Split()
	fmt.Println()
	fmt.Println("unicode")
	for n,ch := range s{
		fmt.Printf("|%d %X| ",n,ch) //ch is a rune  (int32)
	}
	fmt.Println()
	fmt.Println("Rune count:",utf8.RuneCountInString(s))
	fmt.Println("Decode")
	bytes := []byte(s)
	for len(bytes) > 0{
		ch,size := utf8.DecodeRune(bytes)
		bytes = bytes[size:]
		fmt.Printf("%c",ch)
	}
	fmt.Println()
	for n,ch := range []rune(s){
		fmt.Printf("|%d %c|",n,ch)
	}
}
func main() {
	testChars()
}
posted @ 2018-09-13 01:06  遥望1992  阅读(136)  评论(0编辑  收藏  举报