字串

字串 在 Go

1 個練習

關於 字串

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'
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 字串