概述
Go 中 字符串
语义和其余编程语言中的字符串中一样,有一点不同的中央在于: Go 中字符串值无奈扭转,能够了解为:
一旦实现定义之后,字符串就是一个 常量。
解释型字符串
应用双引号 "
括起来,其中的本义符将被替换,本义符包含:
\n
: 换行符\r
: 回车符\t
: tab 键\u
: 或 \U:Unicode 字符\\
: 反斜杠本身- 其余本义符
示例
package mainfunc main() { s := "hello\nworld" println(s)}// $ go run main.go// 输入如下/** hello world*/
非解释型字符串
应用反引号 ` 括起来,其中的本义符会被原样输入。
示例
package mainfunc main() { s := `hello world \n` println(s)}// $ go run main.go// 输入如下/** hello world \n*/
字符串不可变的语义
字符串的 不可变
是指: 字符串定义之后,每个索引地位的字符不可被批改,如下所示:
package mainfunc main() { s := "hello world" s[0] = 'a' s[1] = 'b'}// $ go run main.go// 输入如下/** ./main.go:5:2: cannot assign to s[0] (value of type byte) ./main.go:6:2: cannot assign to s[1] (value of type byte)*/
然而,能够通过为字符串从新赋值,扭转原有字符串,如下所示:
package mainfunc main() { s := "hello world" s = "hello golang" println(s)}// $ go run main.go// 输入如下/** hello golang*/
字符串长度
对于字符串不同编码对长度的计算形式,感兴趣的读者能够参考扩大浏览。
ASCII
package mainfunc main() { s := "hello world" println(len(s))}// $ go run main.go// 输入如下/** 11*/
中文算作 3 个字符
中文会依照 3 个字节计算,这在一些场景下 (统计时英文和中文都算一个字),可能并不适宜。
package mainfunc main() { s := "hello 世界" println(len(s))}// $ go run main.go// 输入如下/** 12*/
中文算作 1 个字符
package mainimport "unicode/utf8"func main() { s := "hello world" println(utf8.RuneCountInString(s)) s2 := "hello 世界" println(utf8.RuneCountInString(s2)) // 每个中文文字算作一个字符}// $ go run main.go// 输入如下/** 11 8*/
子字符串
语法规定
s[i:j]
s 代表字符串变量名称, i 和 j 的取值范畴是 0 到 len(s)
(字符串长度)。如果两个参数都不设置,则取全副字符。
例子
package mainimport "fmt"func main() { s := "hello world" s2 := s[3:5] // 取第 3 个到第 5 个字符 fmt.Printf("s2 = %v, type = %T\n", s2, s2) s3 := s[:] // 取全副字符 fmt.Printf("s3 = %v, type = %T\n", s3, s3)}// $ go run main.go// 输入如下/** s2 = lo, type = string s3 = hello world, type = string*/
字符串遍历
为了解决不同编码字符串,请应用 range
。
例子
留神辨别不同编码对遍历后果的影响。
package mainimport "fmt"func main() { str := "hello 世界" // ASCII 编码方式遍历 for i := 0; i < len(str); i++ { fmt.Printf("%c ", str[i]) } fmt.Println() // Unicode 编码方式遍历 for _, s := range str { fmt.Printf("%c ", s) } fmt.Println()}// $ go run main.go// 输入如下/** h e l l o ä ¸ ç h e l l o 世 界*/
字符串拼接
应用 +
package mainfunc main() { s := "hello world" s += " !" println(s)}// $ go run main.go// 输入如下/** hello world !*/
应用 fmt.Sprintf() 函数
package mainimport "fmt"func main() { s := "hello world" s2 := fmt.Sprintf("%s %s", s, " !") println(s2)}// $ go run main.go// 输入如下/** hello world !*/
扩大浏览
- 十分钟搞清字符集和字符编码