go語言學習十八 - len(string) = the number of bytes.


package main import ( "fmt" ) func main() { s := "你好,世界.æ" for i, b := range []byte(s) { fmt.Printf("%d %d\n", i, b) //i=0~15 ; 3*4+2*1+1*2 = 16 } n := len(s) //len(string) = the number of bytes. for i:=0;i<n;i++ { fmt.Printf("%d %d\n", i, s[i]) //效果同上 } for i, c := range s { //按rune字符迭代 fmt.Printf("%d %d %c \n", i, c,c) //0 20320 你,1 22909 好,2 44 ,,3 19990 世,4 30028 界,5 46 .,6 230 æ // string(c) 字符轉為字符串 , []byte(s) 字符串轉byte數組:byte數組和字符串的轉換效率非常高 O(1) fmt.Println([]byte(string(b))) /* 這里可以很清楚的看到 漢字:3byte; ascii:1byte; 英語音標字符:2byte [228 189 160] [229 165 189] [44] [228 184 150] [231 149 140] [46] [195 166] */ } // The len built-in function returns the length of v, according to its type: // Array: the number of elements in v. // Pointer to array: the number of elements in *v (even if v is nil). // Slice, or map: the number of elements in v; if v is nil, len(v) is zero. // String: the number of bytes in v. // Channel: the number of elements queued (unread) in the channel buffer; // if v is nil, len(v) is zero.
//對於指針類型,只有數組的指針可以取 len a := [4]int{1,2,3} fmt.Println(len(a)) //4 fmt.Println(len(&a)) //4 對數組指針取len 就是數組的長度 fmt.Println(len(*&a)) //4 b := []int{1,2,3} fmt.Println(len(b)) //3 //fmt.Println(len(&b)) invalid 對切片引用的指針取 len 是非法的 fmt.Println(len(*&b)) //4 //fmt.Println(len(&s)) invalid 對字符串指針取 len 是非法的。 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM