Go 的字符串类型默认是 UTF-8 编码,当字符为 ASCII 码时占用 1 个字节,其它字符根据需要占用 2-4 个字节,中文编码通常需要 3 个字节。
使用
基本
package main
func main() {
var name string // 声明一个字符串类型的变量
name = "Goland" // 初始化赋值
say := "你好,Go" // 另外也可以同时进行声明和初始化
//格式化输出 使用占位符和 转义符
fmt.Printf("Name is : %s,\n Say: %s", name,say)
}
//结果为
Name is : Goland,
Say: 你好,Go
使用 ` 符号
str := `One needs 3 things to be truly happy living
-in the world: some thing to do,
- some one to love, some thing to hope for.
`
fmt.Println(str)
//结果为:
One needs 3 things to be truly happy living
-in the world: some thing to do,
- some one to love, some thing to hope for.
字符串连接
package main
import (
"fmt"
"strconv"
"time"
)
func main() {
Y, m, d := time.Now().Date()
str := "Life is a journey, not the destination,"
str2 := "but the scenery along the should be and the mood at the view.\n"
str3 := str + str2 + "DATE:" + strconv.Itoa(Y) + "-" + strconv.Itoa(int(m)) + "-" + strconv.Itoa(d)
fmt.Println(str3)
}
//结果
Life is a journey, not the destination,but the scenery along the should be and t
he mood at the view.
DATE:2022-7-10
切片方式截取字符串
name := "Chris"
ch := string(name[0]) // 通过类型转换 将uint8 转为 string 否则得到的是字符的ASCII码
fmt.Printf("%s", ch) // C
name := "Chris"
ch := string(name[:4]) // 去掉最后的s , 切片的右下标是闭区间,左下标是开区间
fmt.Printf("%s", ch) // Chri
// 如果是中文,会发现以上出现乱码,中文的遍历实现
name := []rune("克里斯") // 转换为 rune 类型
for _, ch := range name {
fmt.Println(string(ch))
} //克
里
斯
fmt.Println(string(name[:3])) //克里斯
底层的字符类型支持
Go 语言对字符串中的单个字符进行了单独的类型支持,在 Go 语言中支持两种字符类型:
- 一种是
byte
,代表 UTF-8 编码中单个字节的值(它也是uint8
类型的别名,两者是等价的,因为正好占据 1 个字节的内存空间); - 另一种是
rune
,代表单个 Unicode 字符(它也是int32
类型的别名,因为正好占据 4 个字节的内存空间。关于rune
相关的操作,可查阅 Go 标准库的 unicode 包)。