golang——rune使用详解

栏目: Go · 发布时间: 7年前

内容简介:经常在开源库中,能rune关键字,从golang源码中看出,它是int32的别名(-2由于rune可表示的范围更大,所以能处理一切字符,当然也包括中文字符。在平时计算中文字符,可用rune。

一、定义

经常在开源库中,能rune关键字,从golang源码中看出,它是int32的别名(-2 31~2 31-1),对于byte(-128~127),可表示的字符更多。

二、使用

由于rune可表示的范围更大,所以能处理一切字符,当然也包括中文字符。在平时计算中文字符,可用rune。

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    var chinese = "我是中国人, I am Chinese"
    fmt.Println("chinese length", len(chinese))
    fmt.Println("chinese word length", len([]rune(chinese)))
    fmt.Println("chinese word length", utf8.RuneCountInString(chinese))
}
//输出,注意在golang中一个汉字占3个byte
chinese length 31
chinese word length 19
chinese word length 19

以上所述就是小编给大家介绍的《golang——rune使用详解》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Understanding Computation

Understanding Computation

Tom Stuart / O'Reilly Media / 2013-6-3 / USD 39.99

Finally, you can learn computation theory and programming language design in an engaging, practical way. Understanding Computation explains theoretical computer science in a context you'll recognize, ......一起来看看 《Understanding Computation》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具