Go语言入门:string、rune
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
-
21
Convert between rune array/slice and string yourbasic.org/golang Convert string to runes When you...
-
5
How to reverse a string by byte or rune yourbasic.org/golang Byte by byte It’s pretty stra...
-
10
Go语言||字符数据类型 rune和byte mb5fe94b3e552d9 · 大约5小时之前 · 20 次点击 · 预计阅读时间 1 分钟 · 不到1分钟之前 开始浏览 ...
-
3
rune是int32的别名类型,一个值就代表一个Unicode字符。 byte是uint8的别名类型,一个值就代表一个ASCII码的一个字符。 rune类型的值在底层都是由一个 UTF-8 编码值来表达的。 了解下什么是Unicode字符和ASCII码:...
-
8
How smart crypto traders caught a 48% price pump – HodlalertA RUNE with a view: How smart crypto traders caught a 48% price pump
-
2
R ust UN der E macs This project is an experimental Emacs lisp interpreter written in rust. The project is still at a very early phase and explores using rust as an host language. Status The goal o...
-
6
[Golang] Check If The Rune is Chinese Character October 11, 2018 Given a
-
6
Contributing to the Rune Project Getting Started The rune project is just another Rust project and can be compiled using cargo. $ git clone https://github.com/hotg-ai/rune.git $ cd run...
-
4
golang中string,rune,byte的关系 发表于 2018-10-25...
-
0
你知道Go语言的Rune吗? 作者:程序员升级打怪之旅 2022-10-24 09:57:02 由于rune可表示的范围更大,所以能处理一切字符,当然也包括中文字符。在平时计算中文字符,可用rune。当我们数据中有中文时,一定要注意ru...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK