赶知识网

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

2017-08-03 / 2911次点击 golang
一、获取字符串长度的几种方法
- 使用 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,"")-1
l4:=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  (如果是纯英文字符的字符串,可以使用来判断字符串的长度)
有用 0 没用 0

Top10

沪ICP备09053415号 © 赶知识网