• go语言:获取字符串长度


    go语言字符串底层由字节数组实现,使用UTF-8编码,初始化以后不能被修改

    获取字符串长度

    一、当字符串中所有字符都是单字节字符时,使用 len 函数获取字符串的长度

    package main
    
    import "fmt"
    
    func main() {
        var str string
        str = "Hello world"
        fmt.Printf("The length of "%s" is %d. 
    ", str, len(str))
    }
    

    以上程序输入结果为:The length of "Hello world" is 11.

    二、当字符串中包含多字节字符时,有两种方式获取字符串的长度

    1、用到标准库 utf8 中的 RuneCountInString 函数来获取字符串的长度

    package main
    
    import (
    	"fmt"
    	"unicode/utf8"
    )
    
    func main() {
        str := "Hello, 世界"
    fmt.Println("bytes =", len(str)) fmt.Println("runes =", utf8.RuneCountInString(str)) }

    以上程序输入结果为:

    bytes = 13
    runes = 9

    2、向将字符串转换为rune切片,然后通过 len 函数获取长度

    package main
    
    import (
    	"fmt"
    )
    
    func main() {
    	str := "Hello, 世界"
    	runes := []rune(str)
    	fmt.Printf("The byte length of "%s" a is %d 
    ", str, len(str))
    	fmt.Printf("The length of "%s" a is %d 
    ", str, len(runes))
    }
    

    以上程序输出:

    The byte length of "Hello, 世界" a is 13
    The length of "Hello, 世界" a is 9

      

  • 相关阅读:
    定义字符串数组
    ifconfig 修改IP
    空指针与野指针的区别
    GDB和Core Dump使用笔记
    雅虎(ycsb)测试hbase(压测)
    decode函数的几种用法
    NVL函数:空值转换函数
    hive行转列,列转行
    case when then else end用法
    hive中一般取top n时,row_number(),rank,dense_ran()常用三个函数
  • 原文地址:https://www.cnblogs.com/liyuchuan/p/11081105.html
Copyright © 2020-2023  润新知