Go by Example 中文版: 字符串和rune类型
source link: https://gobyexample-cn.github.io/strings-and-runes
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.
Go by Example 中文版: 字符串和rune类型
Go语言中的字符串是一个只读的byte类型的切片。
Go语言和标准库特别对待字符串 - 作为以
UTF-8 为编码的文本容器。
在其他语言当中, 字符串由”字符”组成。
在Go语言当中,字符的概念被称为 |
|
package main |
|
import ( "fmt" "unicode/utf8" ) |
|
func main() { |
|
|
const s = "สวัสดี" |
因为字符串等价于 |
fmt.Println("Len:", len(s)) |
对字符串进行索引会在每个索引处生成原始字节值。
这个循环生成构成 |
for i := 0; i < len(s); i++ { fmt.Printf("%x ", s[i]) } fmt.Println() |
要计算字符串中有多少rune,我们可以使用 |
fmt.Println("Rune count:", utf8.RuneCountInString(s)) |
|
for idx, runeValue := range s { fmt.Printf("%#U starts at %d\n", runeValue, idx) } |
我们可以通过显式使用 |
fmt.Println("\nUsing DecodeRuneInString") for i, w := 0, 0; i < len(s); i += w { runeValue, width := utf8.DecodeRuneInString(s[i:]) fmt.Printf("%#U starts at %d\n", runeValue, i) w = width |
这演示了将 |
examineRune(runeValue) } } |
func examineRune(r rune) { |
|
用单引号括起来的值是 rune literals.
我们可以直接将 |
if r == 't' { fmt.Println("found tee") } else if r == 'ส' { fmt.Println("found so sua") } } |
$ go run strings-and-runes.go Len: 18 e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5 Rune count: 6 U+0E2A 'ส' starts at 0 U+0E27 'ว' starts at 3 U+0E31 'ั' starts at 6 U+0E2A 'ส' starts at 9 U+0E14 'ด' starts at 12 U+0E35 'ี' starts at 15 |
|
Using DecodeRuneInString U+0E2A 'ส' starts at 0 found so sua U+0E27 'ว' starts at 3 U+0E31 'ั' starts at 6 U+0E2A 'ส' starts at 9 found so sua U+0E14 'ด' starts at 12 U+0E35 'ี' starts at 15 |
下一个例子: 结构体
@mmcgrana 和Eli Bendersky编写 | gobyexample-cn 翻译 | 反馈 | 源码 | license
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK