利用golang怎么獲取字符串的個(gè)數(shù)

這篇文章將為大家詳細(xì)講解有關(guān)利用golang怎么獲取字符串的個(gè)數(shù),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

吳川網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)建站,吳川網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為吳川上1000+提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)公司要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的吳川做網(wǎng)站的公司定做!

在 golang 中不能直接用 len 函數(shù)來統(tǒng)計(jì)字符串長度,查看了下源碼發(fā)現(xiàn)字符串是以 UTF-8 為格式存儲(chǔ)的,說明 len 函數(shù)是取得包含 byte 的個(gè)數(shù)

// string is the set of all strings of 8-bit bytes, conventionally but not
// necessarily representing UTF-8-encoded text. A string may be empty, but
// not nil. Values of string type are immutable.

舉個(gè)例子,”Hello, 世界“(因?yàn)椋瑢?duì)比所以用了中文)

s := "Hello, 世界"
fmt.Println(len(s)) // 13
fmt.Println([]byte(s)) // [72 101 108 108 111 44 32 228 184 150 231 149 140]

既然是以 byte 存儲(chǔ)的,那自然就想到了取 byte 的長度

- bytes.Count() 
- strings.Count() 
- 將字符串轉(zhuǎn)換為 []runee 后調(diào)用 len 函數(shù)
- 使用 utf8.RuneCountInString()
package main
import (
  "bytes"
  "fmt"
  "strings"
  "testing"
  "unicode/utf8"
)
/*
在 golang 中不能直接用 len 函數(shù)來統(tǒng)計(jì)字符串長度,查看了下源碼發(fā)現(xiàn)字符串是以 UTF-8 為格式存儲(chǔ)的,說明 len 函數(shù)是取得包含 byte 的個(gè)數(shù)
*/
func main() {
  s := "hello, 世界"
  fmt.Println(len(s))  // 13
  fmt.Println([]byte(s)) // [72 101 108 108 111 44 32 228 184 150 231 149 140]
  fmt.Print(f1(s))
}
func f1(s string) int {
  return bytes.Count([]byte(s), nil) - 1
}
func f2(s string) int {
  return strings.Count(s, "") - 1
}
func f3(s string) int {
  return len([]rune(s))
}
func f4(s string) int {
  return utf8.RuneCountInString(s)
}
var s = "Hello, 世界"
func Benchmark1(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f1(s)
  }
}
func Benchmark2(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f2(s)
  }
}
func Benchmark3(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f3(s)
  }
}
func Benchmark4(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f4(s)
  }
}

在 golang ldea配置中我沒有看到 benchamark配置,總說包不對(duì),在命令行中輸入

go test stringCount_test.go -bench ".*"

得到以下結(jié)果

Benchmark1-12           100000000               17.7 ns/op
Benchmark2-12           100000000               14.0 ns/op
Benchmark3-12           100000000               14.5 ns/op
Benchmark4-12           100000000               13.1 ns/op

關(guān)于利用golang怎么獲取字符串的個(gè)數(shù)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

本文標(biāo)題:利用golang怎么獲取字符串的個(gè)數(shù)
網(wǎng)址分享:http://muchs.cn/article42/gphcec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站、手機(jī)網(wǎng)站建設(shè)、用戶體驗(yàn)、服務(wù)器托管、App設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司