59_Go基础_1_26 字符串

 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6     /*
 7         Go中的字符串是一个字节的切片。
 8             可以通过将其内容封装在“”中来创建字符串。Go中的字符串是Unicode兼容的,并且是UTF-8编码的。
 9 
10         字符串是一些字节的集合。
11             理解为一个字符的序列。
12             每个字符都有固定的位置(索引,下标,index:从0开始,到长度减1)
13 
14         语法:"",``
15             ""
16             "a","b","中"
17             "abc","hello"
18         字符:--->对应编码表中的编码值
19             A-->65
20             B-->66
21             a-->97
22             ...
23 
24         字节:byte-->uint8
25             utf8
26     */
27 
28     // 1.定义字符串
29     s1 := "hello中国"
30     s2 := `hello world`
31     fmt.Println(s1)
32     fmt.Println(s2)
33 
34     // 2.字符串的长度:返回的是字节的个数
35     fmt.Println(len(s1)) // 11
36     fmt.Println(len(s2)) // 11
37 
38     // 3.获取某个字节
39     fmt.Println(s2[0]) // 获取字符串中的第一个字节 104
40     a := 'h'
41     b := 104
42     fmt.Printf("%c,%c,%c\n", s2[0], a, b) // h,h,h
43 
44     // 4.字符串的遍历
45     for i := 0; i < len(s2); i++ {
46         //fmt.Println(s2[i])      // 数字
47         fmt.Printf("%c\t", s2[i]) // 字符
48     }
49     fmt.Println()
50 
51     // for range
52     for _, v := range s2 {
53         // fmt.Println(v)   // 数字
54         fmt.Printf("%c", v) // 字符 hello world
55     }
56     fmt.Println()
57 
58     // 5.字符串是字节的集合
59     slice1 := []byte{65, 66, 67, 68, 69}
60     s3 := string(slice1) // 根据一个字节切片,构建字符串
61     fmt.Println(s3)      // ABCDE
62 
63     s4 := "abcdef"
64     slice2 := []byte(s4) // 根据字符串,获取对应的字节切片
65     fmt.Println(slice2)  // [97 98 99 100 101 102]
66 
67     // 6.字符串不能修改
68     fmt.Println(s4)
69     // s4[2] = 'B'  // cannot assign to s4[2] (strings are immutable)
70 }