首页 > 其他分享 >0090-Go-字符串

0090-Go-字符串

时间:2022-10-30 08:34:32浏览次数:71  
标签:Println const fmt 字符串 Go import main 0090

环境

  • 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 语言的字符串。

附录

标签:Println,const,fmt,字符串,Go,import,main,0090
From: https://www.cnblogs.com/jiangbo4444/p/16840460.html

相关文章

  • 0091-Go-结构体
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/structs目标使用Go语言的结构体。直接使用结构体packagemainimport"fmt"typeperson......
  • 0092-Go-方法
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/methods目标使用Go语言的方法。值方法packagemainimport"fmt"typerectstruct{......
  • 0093-Go-接口
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/interfaces目标使用Go语言的接口。定义接口typegeometryinterface{area()float64......
  • 0094-Go-结构体嵌入
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/struct-embedding目标使用Go语言的结构体嵌入。定义结构体typebasestruct{numint......
  • 0095-Go-泛型
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/generics目标使用Go语言的泛型。泛型函数packagemainimport"fmt"funcMapKeys[Kcom......
  • 0075-Go-变量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/variables目标使用Go语言变量的申明和使用变量。示例packagemainimport"fmt"funcma......
  • 0076-Go-常量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/constants目标使用Go语言的常量。示例packagemainimport("fmt""math")co......
  • 0077-Go-for 循环
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/for目标使用Go语言的for循环。单条件循环类似其它语言中的while循环。packagemain......
  • 0078-Go-if else 条件判断
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/if-else目标使用Go语言的if/else条件判断。条件判断条件判断的小括号可以省略,但是后面的......
  • 0079-Go-switch 分支
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/switch目标使用Go语言的switch分支语句。整数分支packagemainimport"fmt"funcmai......