golang中擷取字串長度的幾種方法

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

一、擷取字串長度的幾種方法

- 使用 bytes.Count() 統計- 使用 strings.Count() 統計- 將字串轉換為 []rune 後調用 len 函數進行統計- 使用 utf8.RuneCountInString() 統計

例:

str:="HelloWord"l1:=len([]rune(str))l2:=bytes.Count([]byte(str),nil)-1)l3:=strings.Count(str,"")-1l4:=utf8.RuneCountInString(str)fmt.Println(l1)
fmt.Println(l2)
fmt.Println(l3)
fmt.Println(l4)
列印結果:都是 9

二、strings.Count函數和bytes.Count函數

這兩個函數的用法是相同,只是一個作用在字串上,一個作用在位元組上


strings中的Count方法

func Count(s, sep string) int{}
   判斷字元sep在字串s中出現的次數,沒有找到則返回-1,如果為空白字串("")則返回字串的長度+1

例:

str:="HelloWorld"fmt.Println(strings.Count(str,"o"))  //列印 o 出現的次數,列印結果為2

 註:在 Golang 中,如果字串中出現中文字元不能直接調用 len 函數來統計字串字元長度,這是因為在 Go 中,字串是以 UTF-8 為格式進行儲存的,在字串上調用 len 函數,取得的是字串包含的 byte 的個數。

str:="HelloWorld"

str1 := "Hello, 世界"fmt.Println(len(str1)) // 列印結果:13
fmt.Println(len(str))  //列印結果:9  (如果是純英文字元的字串,可以使用來判斷字串的長度)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.