zoukankan      html  css  js  c++  java
  • Strings, bytes, runes and characters in Go

    原文地址

    https://blog.golang.org/strings

    示例

    package main
    
    import (
        "fmt"
        "unicode/utf8"
    )
    
    func main() {
        const sample = "xbdxb2x3dxbcx20xe2x8cx98"
        // sample len:  8
        fmt.Println("sample len: ", len(sample))
    
        // bd b2 3d bc 20 e2 8c 98
        for i := 0; i < len(sample); i++ {
            fmt.Printf("%x ", sample[i])
        }
    
        // bdb23dbc20e28c98
        // bdb23dbc20e28c98 
        // "xbdxb2=xbc ⌘"
        // "xbdxb2=xbc u2318"
        fmt.Printf("%x
    ", sample)
    
        fmt.Printf("%x 
    ", sample)
    
        fmt.Printf("%q
    ", sample)
    
        fmt.Printf("%+q
    ", sample)
    
        fmt.Println("======================")
    
        const placeOfInterest = `⌘`
        // placeOfInterest len:  3
        fmt.Println("placeOfInterest len: ", len(placeOfInterest))
    
        // plain string:
        //
        fmt.Println("plain string:")
        fmt.Printf("%s", placeOfInterest)
        fmt.Printf("
    ")
    
        // quoted string:"u2318"
        fmt.Printf("quoted string:")
        fmt.Printf("%+q", placeOfInterest)
        fmt.Printf("
    ")
    
        // hex bytes:e28c98
        fmt.Printf("hex bytes:")
        for i := 0; i < len(placeOfInterest); i++ {
            fmt.Printf("%x", placeOfInterest[i])
        }
        fmt.Printf("
    ")
    
        fmt.Println("=================")
    
        const nihongo = "日本語"
        // nihongo len:  9
        fmt.Println("nihongo len: ", len(nihongo))
        
        // U+65E5 '日' starts at byte position 0
        // U+672C '本' starts at byte position 3
        // U+8A9E '語' starts at byte position 6
        for index, runeValue := range nihongo {
            fmt.Printf("%#U starts at byte position %d
    ", runeValue, index)
        }
    
    
        // U+65E5 '日' starts at byte position 0
        // U+672C '本' starts at byte position 3
        // U+8A9E '語' starts at byte position 6
        for i, w := 0, 0; i < len(nihongo); i += w {
            runeValue, width := utf8.DecodeRuneInString(nihongo[i:])
            fmt.Printf("%#U starts at byte position %d
    ", runeValue, i)
            w = width
        }
    }

    整体上本篇blog主要讲了字符串,字节,符文,字符的包含于转换关系,大道至简,只需要有一个概念,那就是计算机上的任何字符串都是底层的字节表示,因为计算机底层就是01,再通过不同的标准来转换输出而已。

    前言,不可能每个人都有Rob Pike的实力,但是要有他的态度。

    end

    一个没有高级趣味的人。 email:hushui502@gmail.com
  • 相关阅读:
    外媒评出的中国最美的地方
    外媒评出的中国最美的地方
    中国十大徒步路线,你走过几个?
    中国十大徒步路线,你走过几个?
    还在用Ghost?Windows 7时代用True Image了
    查看手机已经记住的WIFI密码
    查看手机已经记住的WIFI密码
    量子力学的经典教材
    量子力学的经典教材
    索尼全画幅微单A7/A7R上市
  • 原文地址:https://www.cnblogs.com/CherryTab/p/12763068.html
Copyright © 2011-2022 走看看