10.字符串原理解析
a.字符串底层就是一个byte数组,所以可以和[]byte类型互相转换
b.字符串之中的字符是不能修改的,想要修改只能用byte切片来修改
1: package main2:3: import (
4: "fmt"
5: )6:7: func testString(){8: var str string = "hello"9: fmt.Printf("str[0]=%c len(str)=%d ", str[0], len(str))
10: for index, val := range str {
11: fmt.Printf("str[%d]=%c ", index, val)12: }13: // 定义byte切片
14: var byteSlice []byte15: byteSlice = []byte(str)16: byteSlice[0] = 'o'17: str = string(byteSlice)
18: fmt.Println(str)19: }20:21: func main() {22: testString()23: }
c.字符串是byte字节组成,所以字符串的长度是byte字节的长度
d.rune类型用来表示utf8字符,一个rune字符由1个或多个byte组成
1: var b rune = '中'2: str = "中文123"
3: fmt.Printf("b=%c ", b)
4: var runeSlice []rune5: runeSlice = []rune(str)6: fmt.Printf("str长度=%d len(str)=%d ", len(runeSlice), len(str))
几个关于字符串的练习:
test1:对英文字符串进行逆序
1: func test1(){2: var str = "hello"
3: // var bytes []byte = []byte(str)
4: bytes := []byte(str)5: for i :=0; i < len(str)/2; i++ {6: tmp := bytes[len(str)-i-1]7: bytes[len(str)-i-1] = bytes[i]8: bytes[i] = tmp9: }10: str = string(bytes)
11: fmt.Println(str)12: }
test2:对包含中文的字符串进行逆序
1: func test2(){2: var str = "hello,你好"
3: runes := []rune(str)4:5: for i:=0; i < len(runes)/2; i++ {6: tmp := runes[len(runes)-i-1]7: runes[len(runes)-i-1] = runes[i]8: runes[i] = tmp9: }10: str = string(runes)
11: fmt.Println(str)12: }
test3:判断一个字符串是否是回文
1: func test3() {2: var str = "上海自来水来自海上"
3: runes := []rune(str)4: for i:=0; i < len(runes)/2; i++ {5: tmp := runes[len(runes)-i-1]6: runes[len(runes)-i-1] = runes[i]7: runes[i] = tmp8: }9: str_2 := string(str)
10: if str == str_2 {
11: fmt.Println("yes")
12: }else{
13: fmt.Println("no")
14: }15: }