原文地址
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