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

这篇文章主要介绍了go语言如何获取字符串长度的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇go语言如何获取字符串长度文章都会有所收获,下面我们一起来看看吧。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名、网页空间、营销软件、网站建设、长葛网站维护、网站推广。

获取方法: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 即可。

示例:

package main
import (
	"bytes"
	"fmt"
)
func main() {
	//使用 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 函数,第二个参数是子串,传入空即可。

示例:

package main
import (
	"fmt"
	"strings"
)
func main() {
	//使用 strings.Count() 获取字符串长度
	strHaiCoder := "(Hello, 创新互联)"
	strCount := strings.Count(strHaiCoder, "")
	fmt.Println("strCount =", strCount)
}

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

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

len([]rune(str))

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

返回值:

  • 返回字符串长度。

说明:

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

示例:

package main
import (
	"fmt"
)
func main() {
	//使用 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() 获取字符串长度。

示例:

package main
import (
	"fmt"
	"unicode/utf8"
)
func main() {
	//使用 utf8.RuneCountInString() 获取字符串长度
	strHaiCoder := "(Hello, 创新互联)"
	strCount := utf8.RuneCountInString(strHaiCoder)
	fmt.Println("strCount =", strCount)
}

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

关于“go语言如何获取字符串长度”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“go语言如何获取字符串长度”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。


网站栏目:go语言如何获取字符串长度
链接分享:http://pwwzsj.com/article/jpohid.html