0090-Go-字符串

环境

  • Time 2022-08-23
  • Go 1.19

前言

说明

参考:https://gobyexample.com/strings-and-runes

目标

使用 Go 语言的字符串。

字节遍历

package main

import "fmt"

func main() {
    const s = "你好啊"
    fmt.Println("Len:", len(s))

    for i := 0; i < len(s); i++ {
        fmt.Printf("%x ", s[i])
    }
    fmt.Println()
}

字符计数

字符在 go 中称为 rune。

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    const s = "你好啊"
    fmt.Println("Rune count:", utf8.RuneCountInString(s))
}

字符遍历

package main

import "fmt"

func main() {

    const s = "你好啊"
    for idx, runeValue := range s {
        fmt.Printf("%#U starts at %d\n", runeValue, idx)
    }
}

自实现字符遍历

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {

    const s = "你好啊"

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

总结

使用 Go 语言的字符串。

附录

posted @ 2022-10-30 08:23  jiangbo4444  阅读(23)  评论(0)    收藏  举报