• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

go语言:获取字符串长度

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

go语言字符串底层由字节数组实现,使用UTF-8编码,初始化以后不能被修改

获取字符串长度

一、当字符串中所有字符都是单字节字符时,使用 len 函数获取字符串的长度

package main

import "fmt"

func main() {
    var str string
    str = "Hello world"
    fmt.Printf("The length of \"%s\" is %d. \n", str, len(str))
}

以上程序输入结果为:The length of "Hello world" is 11.

二、当字符串中包含多字节字符时,有两种方式获取字符串的长度

1、用到标准库 utf8 中的 RuneCountInString 函数来获取字符串的长度

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
    str := "Hello, 世界"
fmt.Println("bytes =", len(str)) fmt.Println("runes =", utf8.RuneCountInString(str)) }

以上程序输入结果为:

bytes = 13
runes = 9

2、向将字符串转换为rune切片,然后通过 len 函数获取长度

package main

import (
	"fmt"
)

func main() {
	str := "Hello, 世界"
	runes := []rune(str)
	fmt.Printf("The byte length of \"%s\" a is %d \n", str, len(str))
	fmt.Printf("The length of \"%s\" a is %d \n", str, len(runes))
}

以上程序输出:

The byte length of "Hello, 世界" a is 13
The length of "Hello, 世界" a is 9

 

 

 

 

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap