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

 

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM