42

Go语言入门:string、rune

 4 years ago
source link: http://www.xetlab.com/2020/01/18/Go语言入门:string、rune/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
msg := "hello world"
cnMsg := "你好世界"
multiline := `
				select * from table
				where col='val'
			`

单行的字符串初始化和大部分语言一样,使用双引号,支持和python一样的多行,但是用反单引号,就是键盘上按键区最左上角的那个符号。

长度

msg := "hello world"
fmt.Println(len(msg))
cnMsg := "你好世界"
fmt.Println(len(cnMsg))

上面两个打印字符串长度的代码会输出多少?11和4吗?错了,答案是11和16,len方法取得的结果是字符串所占用的字节数,go语言中的字符串使用的是可变长的UTF8编码,ASCII码占用1个字节,其它字符是2-4个字节,对于中文字符是3个字节。那如何取得我们预想的字符串长度:11和4?可以使用如下的两个方法:

fmt.Println(utf8.RuneCountInString(msg))
fmt.Println(utf8.RuneCountInString(cnMsg))

这里的rune可以认为用于表示一个utf8编码,如果想把汉字字符串,一个个打印出来,可用如下方法实现:

cnMsg := "你好世界"
msgRunes := []rune(cnMsg)
for _, c := range msgRunes {
    fmt.Println(string(c))
}

SLICE

msg := "hello world"
fmt.Println(msg[:5])
fmt.Println(msg[6:])
fmt.Println(msg[3:5])
fmt.Println(msg[0])

对于ASCII码字符串可以使用上面的方法进行类似Java substring的操作,注意最后一个返回的是h的ASCII码值。对于中文字符如果也像上面的方式操作,打印出来的结果会是乱码,因为上面的操作是基于字节索引的,中文的substring要像下面这样操作,先转成rune表示的UTF8编码数组,然后基于UTF8编码索引:

cnMsg := "你好世界"
fmt.Println(string([]rune(cnMsg)[0:1]))

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK