字符串是不可变的字节序列,它可以包含任意数据,包括0值字节 内置的 len 函数返回字符串的字节数。 例: s := "hello,world" fmt.Println(len(s)) // "12" 切片: fmt.Println(s[0:5]) // "hello" 与python基本一致 4个标准包操作对字符串操作 1. strings // 用于搜索、替换、比较、切分、连接字符串 2. bytes // 用于操作字节 slice 3. strconv // 把字符串转换为布尔值、整数、浮点数,另外有为字符串添加/去除引号的函数 4. unicode // 判别字符串值特性的函数,如:IsDigit、IsLetter、IsUpper等 例1:函数向表示十进制非负整数的字符串中插入逗号 package main import "fmt" func comma(s string) string { n := len(s) if n <= 3 { return s } return comma(s[:n-3]) + "," + s[n-3:] //递归调用 } func main() { //comma("12345") fmt.Println(comma("123456789")) } 字符串和字节slice相互转换 s := "abc" b := []byte(s) s2 := string(b) // 概念上,[]byte(s)转换操作会分配新的字节数组,拷贝填入s含有的字节,并生成一个slice引用,指向整个数组。 整数转换成字符串 例: x := 123 y := fmt.Sprintf("%d", x) // 第一种方法 fmt.Println(y, strconv.Itoa(x)) // 第二种方法