go语言如何获取字符串长度(go语言,编程语言)

时间:2024-05-07 10:16:27 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

获取方法:1、使用bytes.Count()获取长度,语法“bytes.Count([]byte(str), sep))”;2、使用strings.Count()获取长度,语法“strings.Count(str, substr)”;3、使用len()获取长度,语法“len([]rune(str))”;4、使用utf8.RuneCountInString()获取长度。

在 Go 语言 中要想获取 字符串 长度有四种方法:

  • 使用 bytes.Count()

  • 使用 strings.Count()

  • 使用 len()

  • 使用 utf8.RuneCountInString()

方法1:使用bytes.Count()获取长度

bytes.Count([]byte(str),sep))

参数描述str要获取长度的字符串。sep分隔符,一般传 nil。

返回值:

  • 返回字符串长度。

说明:

  • 我们需要将字符串强转成 byte 数组,传入 bytes.Count 函数,第二个参数是分隔符,传入 nil 即可。

示例:

packagemainimport( "bytes" "fmt")funcmain(){ //使用bytes.Count()获取字符串长度 strHaiCoder:="(Hello,)" strCount:=bytes.Count([]byte(strHaiCoder),nil) fmt.Println("strCount=",strCount)}

go语言如何获取字符串长度

方法2:使用strings.Count()获取长度

strings.Count(str,substr)

参数描述str要获取长度的字符串。substr子串,传入空即可。

返回值:

  • 返回字符串长度。

说明:

  • 我们直接将字符串传入 strings.Count 函数,第二个参数是子串,传入空即可。

示例:

packagemainimport( "fmt" "strings")funcmain(){ //使用strings.Count()获取字符串长度 strHaiCoder:="(Hello,)" strCount:=strings.Count(strHaiCoder,"") fmt.Println("strCount=",strCount)}

go语言如何获取字符串长度

方法3:使用len()获取长度

len([]rune(str))

参数描述str要获取长度的字符串。

返回值:

  • 返回字符串长度。

说明:

  • 我们需要将字符串强转成 rune 数组,传入 len 函数。

示例:

packagemainimport( "fmt")funcmain(){ //使用len()获取字符串长度 strHaiCoder:="(Hello,)" strCount:=len(strHaiCoder) strCount2:=len([]rune(strHaiCoder)) fmt.Println("strCount=",strCount,"strCount2=",strCount2)}

go语言如何获取字符串长度

方法4:使用utf8.RuneCountInString()获取长度

utf8.RuneCountInString(str)

参数描述str要获取长度的字符串。

返回值:

  • 返回字符串长度。

说明:

  • 我们可以使用 utf8.RuneCountInString() 获取字符串长度。

示例:

packagemainimport( "fmt" "unicode/utf8")funcmain(){ //使用utf8.RuneCountInString()获取字符串长度 strHaiCoder:="(Hello,)" strCount:=utf8.RuneCountInString(strHaiCoder) fmt.Println("strCount=",strCount)}

go语言如何获取字符串长度

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:go语言如何获取字符串长度的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:【翻译】ExtJS vs AngularJS下一篇:

11 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18