Go 中的string是不可变的字节序列,这些字节不一定代表字符。
字符串字面量定义在双引号之间:
const name = "Jane"
字符串可以通过+运算符拼接:
"Jane" + " " + "Austen"
// => "Jane Austen"
有些特殊字符需要用反斜杠转义,例如字符串中的\t表示制表符,\n表示换行。
"How is the weather today?\nIt's sunny"
// =>
// How is the weather today?
// It's sunny
strings包提供了许多处理字符串的实用函数。
想了解更多关于字符串函数的信息,请查阅 strings 包文档。
下面是一些例子:
import "strings"
// strings.ToLower returns the string given as argument with all its characters lowercased
strings.ToLower("MaKEmeLoweRCase")
// => "makemelowercase"
// strings.Repeat returns a string with a substring given as argument repeated many times
strings.Repeat("Go", 3)
// => "GoGoGo"
前面提到,有些特殊字符需要用反斜杠转义。 下面是这些特殊字符的更详细的列表:
| 值 | 说明 |
|---|---|
\a |
警报或响铃 |
\b |
退格 |
\\ |
反斜杠 |
\t |
水平制表符 |
\n |
换行符 |
\f |
换页 |
\r |
回车 |
\v |
垂直制表符 |
\' |
单引号 |
\" |
双引号 |
fmt.Println("Joe\nWilliam\nJack\nAverell")
// Output:
// Joe
// William
// Jack
// Averell
原始字符串字面量使用反引号(`)作为分隔符,而不是双引号,其中的所有字符都按字面解释,也就是说不需要转义字符或换行。
下面是一个多行字符串的例子:
const daltons = `Joe
William
Jack
Averell`
这个字符串有多行。
具体来说,它有 3 个\n。
不过,因为它是一个原始字符串字面量,我们不需要在字符串中显式地写出\n。
换行会被按字面解释。
下面还有一些其他的例子,比较原始字符串字面量和常规字符串字面量:
`abc`
// same as "abc"
"\"" // regular string literal with 1 character: a double quote
// same as `"` a raw string literal with 1 character: a double quote
`\n
` // raw string literal with 3 character: a backslash, an 'n', and a newline
// same as "\\n\n" a regular string literal with 3 characters: a backslash, an 'n', and a newline
"\t\n" // regular string literal with 2 characters: a tab and a newline
`\t\n`// raw string literal with 4 characters: two backslashes, a 't', and an 'n'