Go语言中字符串的使用方法

主要讲解Go语言中字符串的使用方法

知识点:

  • 使用range遍历字符串,获取到的是字节,无法获取中文字符,验证了在UTF-8编码中 一个汉字占三个字节
  • 使用 utf8.RuneCountInString(s)) 获取字符串长度,可以正常解析中文,一个中文被当做一个字符。
  • 使用 len(string) 获取字节的长度
  • 使用 []byte(s) 获取字节
  • 使用 []rune(s) 获取字符,可对中文进行转换

以下为代码示例:

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	//默认情况下,Go使用UTF-8编码,此编码下,一个中文汉字占3个字节
	//GBK、GB2312收编的汉字占2个字节,
	// 严格地用iso8859-1无法表示汉字,只能转为问号。
	s := "Yes我爱我家!" // UTF-8
	fmt.Println(s)

	for _, b := range []byte(s) {
		fmt.Printf("%X ", b) 
		//59 65 73 E6 88 91 E7 88 B1 E6 88 91 E5 AE B6 21 
	}
	fmt.Println()

	//下面这种遍历方式 是按字节 来进行计算的
	for i, ch := range s { // ch is a rune
		// 会将字符转换为 unicode 编码,unicode中一个 汉字长度为两个字节
		fmt.Printf("(%d %X) ", i, ch)
	}
	fmt.Println()

	//将字符串的每一个字符转为 rune ,会达到预期效果
	fmt.Println("Rune count:",
		utf8.RuneCountInString(s)) //Rune count: 8

	bytes := []byte(s)
	for len(bytes) > 0 {
		ch, size := utf8.DecodeRune(bytes)
		bytes = bytes[size:]
		fmt.Printf("%c ", ch) //Y e s 我 爱 我 家 !
	}
	fmt.Println()

	for i, ch := range []rune(s) {
		fmt.Printf("(%d %c) ", i, ch)
		//(0 Y) (1 e) (2 s) (3 我) (4 爱) (5 我) (6 家) (7 !)
	}
	fmt.Println()
}

猜你喜欢

转载自my.oschina.net/ruoli/blog/1815552