golang中获取字符串长度的几种方法

一、获取字符串长度的几种方法

  1.  
    - 使用 bytes.Count() 统计
  2.  
    - 使用 strings.Count() 统计
  3.  
    - 将字符串转换为 []rune 后调用 len 函数进行统计
  4.  
    - 使用 utf8.RuneCountInString() 统计

例:

  1.  
    str:="HelloWord"
  2.  
    l1:=len([]rune(str))
  3.  
    l2:=bytes.Count([]byte(str),nil)-1)
  4.  
    l3:=strings.Count(str,"")-1
  5.  
    l4:=utf8.RuneCountInString(str)
  6.  
    fmt.Println(l1)
  7.  
    fmt.Println(l2)
  8.  
    fmt.Println(l3)
  9.  
    fmt.Println(l4)
  10.  
    打印结果:都是 9

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

这两个函数的用法是相同,只是一个作用在字符串上,一个作用在字节上


strings中的Count方法

func Count(s, sep string) int{}

   判断字符sep在字符串s中出现的次数,没有找到则返回-1,如果为空字符串("")则返回字符串的长度+1

例:

  1.  
    str:="HelloWorld"
  2.  
    fmt.Println(strings.Count(str,"o"))  //打印 o 出现的次数,打印结果为2

注:在 Golang 中,如果字符串中出现中文字符不能直接调用 len 函数来统计字符串字符长度,这是因为在 Go 中,字符串是以 UTF-8 为格式进行存储的,在字符串上调用 len 函数,取得的是字符串包含的 byte 的个数。

  1.  
    str:="HelloWorld"
  2.  
     
  3.  
    str1 := "Hello, 世界"
  4.  
    fmt.Println(len(str1)) // 打印结果:13
  5.  
    fmt.Println(len(str)) //打印结果:9 (如果是纯英文字符的字符串,可以使用来判断字符串的长度)
  6.  

原文地址:https://www.cnblogs.com/405845829qq/p/9472955.html