Skip to content

字符串和rune类型

https://gobyexample-cn.github.io/strings-and-runes

Go语言中的字符串是一个只读的byte类型的切片。

Go char 的概念被称为 rune,它是一个表示 Unicode 编码的整数。

用单引号括起来的值是 rune literals,可以与 rune 进行比较

go
func examineRune(r rune) {

    if r == 't' {
        fmt.Println("found tee")
    } else if r == '' {
        fmt.Println("found so sua")
    }
}
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()

    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)
    }
}

utf8.RuneCountInString(s)

todo