美文网首页
golang——rune使用详解

golang——rune使用详解

作者: yushu_bd | 来源:发表于2019-02-11 20:03 被阅读0次

    一、定义

    经常在开源库中,能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使用详解

          本文链接:https://www.haomeiwen.com/subject/itivjqtx.html