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. \n", 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 \n", str, len(str))
	fmt.Printf("The length of \"%s\" a is %d \n", str, len(runes))
}

以上程序输出:

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

 

 

 

 

  

posted @ 2019-09-07 11:23  jacek  阅读(7806)  评论(0编辑  收藏  举报