ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
字符串 1、字符串底层是一个byte(字节)数组,所以可以和[]byte数组类型相互转换。 var str string str = "abc" var b []byte = []byte(str) fmt.Printf("b = %s\n",b) 2、字符串中的字符是不能修改的 3、字符串是由byte字节组成,所以字符串的长度是byte字节的长度 4、rune类型用来表示utf8字符,一个rune字符由一个或多个byte组成 rune是一个utf8的字符,是一个int32的别名。每个字符占4个字节 func strtest() { var str string str = "abc汉字" var b []byte = []byte(str) var c []rune = []rune(str) fmt.Printf("b = %s\n",b) fmt.Printf("len(c) = %v\n",len(c)) fmt.Printf("len(b) = %v\n",len(b)) } 练习1:将英文的字符串进行回返 func hometest() { var str string = "abcdefg" var wang string ="gfedcba" bytes := []byte(str) for i := 0;i < len(str)/2;i++ { //fmt.Printf("i is %s\n",string(str[i])) //fmt.Printf("i is %c\n",str[i]) /*var tmp = bytes[i] bytes[i] = bytes[len(bytes)-i-1] bytes[len(bytes)-i-1] = tmp */ bytes[i],bytes[len(bytes)-i-1] = bytes[len(bytes)-i-1],bytes[i] } str1 := string(bytes) fmt.Printf("str is %s,str1 is %s,\n",str,str1) } 2、将带有中文的字符串回返 func homeChinestest() { var str string = "abcdefg中文" runes := []rune(str) for i := 0;i < len(str)/2;i++ { //fmt.Printf("i is %s\n",string(str[i])) //fmt.Printf("i is %c\n",str[i]) /*var tmp = bytes[i] bytes[i] = bytes[len(bytes)-i-1] bytes[len(bytes)-i-1] = tmp */ runes[i],runes[len(runes)-i-1] = runes[len(runes)-i-1],runes[i] } str = string(runes) fmt.Printf("str is %s\n",str) } 3、判断一个字符串是否为回返 func hometest() { var str string = "abcdefg" var wang string ="gfedcba" bytes := []byte(str) for i := 0;i < len(str)/2;i++ { //fmt.Printf("i is %s\n",string(str[i])) //fmt.Printf("i is %c\n",str[i]) /*var tmp = bytes[i] bytes[i] = bytes[len(bytes)-i-1] bytes[len(bytes)-i-1] = tmp */ bytes[i],bytes[len(bytes)-i-1] = bytes[len(bytes)-i-1],bytes[i] } str1 := string(bytes) fmt.Printf("str is %s,str1 is %s,\n",str,str1) if str1 == wang { fmt.Printf("str1 is equal wang") }else { fmt.Printf("str1 not equal wang") } }