go语言学习十八

package main

import (
	"fmt"
)

func main() {

	s := "你好,世界.æ" 

	for i, b := range []byte(s) {
		fmt.Printf("%d %d
", 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
", i, s[i]) //效果同上
	}

	for i, c := range s {
		//按rune字符迭代
		fmt.Printf("%d %d %c 
", 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 是非法的。 }
原文地址:https://www.cnblogs.com/scala/p/9606770.html