1.字符串表示
在Go语言中不倾向于使用单引号来表示字符串,请根据需要使用双引号或反引号。Go语言中的字符串字面量使用 双引号 或 反引号 来创建:
- 双引号用来创建可解析的字符串字面量(支持转义,但不能用来引用多行);
fmt.Println("How are you?")
fmt.Println("Fine, thank you.And you?")
fmt.Println("I'm fine too.")
- 反引号用来创建原生的字符串字面量,这些字符串可能由多行组成(不支持任何转义序列),原生的字符串字面量多用于书写多行消息、HTML以及正则表达式。
fmt.Println(`
How are you?
Fine, thank you. And you?
I'm fine too.
`)
2.修改字符串的值
- 需要将字符串先转化为slice类型
s := "hello"
c := []byte(s) // 将字符串 s 转换为 []byte 类型
c[0] = 'c'
s2 := string(c) // 再转换回 string 类型
fmt.Printf("%s\n", s2)
- Go中可以使用
+
操作符来连接两个字符串:
s := "hello,"
m := " world"
a := s + m
fmt.Printf("%s\n", a)
- 对字符串切片
s := "hello"
s = "c" + s[1:] // 字符串虽不能更改,但可进行切片操作
fmt.Printf("%s\n", s)
- 声明一个多行的字符串
m := `hello
world`