zoukankan      html  css  js  c++  java
  • rune数据类型 和 strings 的 len 方法

    在学习golang基础的时候,发现有个叫rune的的数据类型,当时不理解这个类型的意义。

    查询,官方的解释如下:

    // rune is an alias for int32 and is equivalent to int32 in all ways. It is
    // used, by convention, to distinguish character values from integer values.
    
    //int32的别名,几乎在所有方面等同于int32
    //它用来区分字符值和整数值
    
    type rune = int32

    这样可能还是对rune的作用与意义比较懵逼,我们通过一个简单的例子来看下rune的作用。先来看下下面这块代码执行结果是什么?

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        str := "hello 你好"
        fmt.Println("len(str):", len(str))
    }

    我们猜测结果应该是“8”:5个字符1个空格2个汉字。那么正确答案是多少呢?

    // MacBook-Pro:rune_jun_2 zhenxink$ go run rune_string_len.go 
    // len(str): 12

    为什么会是12呢? 原因如下:

    /*
    golang中string底层是通过byte数组实现的。中文字符在unicode下占2个字节,在utf-8编码下占3个字节,而golang默认编码正好是utf-8。  
    而且,
    The built-in len function returns the number of bytes(not runes) in a string, and the index operation s[i] retrieves the i-th byte of string s, where 0 <= i < len(s)
    */

    如果我们预期想得到一个字符串的长度,而不是字符串底层占得字节长度,该怎么办呢???

    package main
    
    import (
        "fmt"
        "unicode/utf8"
    )
    
    func main() {
        str := "hello 你好"
    
        //以下两种都可以得到str的字符串长度
    
        //golang中的unicode/utf8包提供了用utf-8获取长度的方法
        fmt.Println("RuneCountInString:", utf8.RuneCountInString(str))
    
        //通过rune类型处理unicode字符
        fmt.Println("rune:", len([]rune(str)))
    }
    
    // MacBook-Pro:rune_jun_2 zhenxink$ go run rune_string_len.go
    // len(str): 12
    // RuneCountInString: 8
    // rune: 8

    golang中还有一个byte数据类型与rune相似,它们都是用来表示字符类型的变量类型。它们的不同在于:

    • byte 等同于int8,常用来处理ascii字符
    • rune 等同于int32,常用来处理unicode或utf-8字符

    参考链接: https://www.jianshu.com/p/4fbf529926ca

  • 相关阅读:
    Linux eclipse 编译C++
    poj2774 Long Long Message(后缀数组or后缀自动机)
    ural 1297 Palindrome(Manacher模板题)
    bzoj 2049 Cave 洞穴勘测(LCT)
    codeforces 519E A and B and Lecture Rooms(LCA,倍增)
    hdu3830 (二分+LCA)
    codeforces 337D Book of Evil(dp)
    codeforces 22C System Administrator(构造水题)
    codeforces 144D Missile Silos(最短路)
    codeforces 505B Mr. Kitayuta's Colorful Graph(水题)
  • 原文地址:https://www.cnblogs.com/neozheng/p/13028917.html
Copyright © 2011-2022 走看看