strconv
最後更新
strconv 套件負責字串與基本型別(整數、浮點數、布林)之間的轉換,以及字串的加引號與去引號。這個套件做什麼
使用者輸入、設定檔、URL 參數、環境變數讀進來都是字串。要拿來計算,就得先把
"42" 轉成整數 42;反過來,要把數字放進訊息或檔案,又得轉回字串。strconv 就是做這件事的工具。| 方向 | 函式 |
|---|---|
| 字串 → 整數 | Atoi、ParseInt、ParseUint |
| 字串 → 浮點數 | ParseFloat |
| 字串 → 布林 | ParseBool |
| 整數 → 字串 | Itoa、FormatInt |
| 浮點數 → 字串 | FormatFloat |
| 加引號、去引號 | Quote、Unquote |
命名規律:
Parse 系列把字串解析成值,會回傳錯誤;Format 系列把值轉成字串,不會失敗;Append 系列把結果接到 []byte 後面。和相近套件的差別:fmt 的
Sprintf("%d", n) 也能把數字轉字串,但 strconv 更快、意圖更明確;把字串轉數字時,strconv 會在格式錯誤時明確回傳錯誤,比 fmt.Sscan 好處理。注意:Go 不能用型別轉換把數字變成字串。
string(65) 得到的是 "A"(碼位 65 的字元),不是 "65",go vet 會對這種寫法發出警告。匯入
- import "strconv"
常用 API
Atoi 與 Itoa
Atoi(ASCII to integer)把十進位字串轉成 int;Itoa 反過來把 int 轉成十進位字串。這是最常用的一對。簽名:
- func Atoi(s string) (int, error)
- func Itoa(i int) string
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- n, err := strconv.Atoi("123")
- fmt.Println(n+1, err)
- _, err = strconv.Atoi("12.5")
- fmt.Println(err)
- _, err = strconv.Atoi(" 7")
- fmt.Println(err)
- s := strconv.Itoa(-45)
- fmt.Printf("%q\n", s)
- }
輸出:
- 124 <nil>
- strconv.Atoi: parsing "12.5": invalid syntax
- strconv.Atoi: parsing " 7": invalid syntax
- "-45"
注意:
Atoi 不會自動去掉空白,前後有空白就會失敗;先用 strings.TrimSpace 處理。ParseInt 與 ParseUint
ParseInt 可以指定進位(base)與位元大小(bitSize)。base 為 0 時會依字首判斷:0x 十六進位、0o 或 0 八進位、0b 二進位。bitSize 是結果要放進的整數寬度(0 代表 int、8、16、32、64),超出範圍會回傳錯誤。回傳值固定是 int64,需要時再轉型。簽名:
- func ParseInt(s string, base int, bitSize int) (i int64, err error)
- func ParseUint(s string, base int, bitSize int) (uint64, error)
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- v, _ := strconv.ParseInt("ff", 16, 64)
- fmt.Println(v)
- v, _ = strconv.ParseInt("0b1010", 0, 64)
- fmt.Println(v)
- v, _ = strconv.ParseInt("1_000_000", 0, 64)
- fmt.Println(v)
- v, err := strconv.ParseInt("300", 10, 8)
- fmt.Println(v, err)
- u, err := strconv.ParseUint("-1", 10, 64)
- fmt.Println(u, err)
- }
輸出:
- 255
- 10
- 1000000
- 127 strconv.ParseInt: parsing "300": value out of range
- 0 strconv.ParseUint: parsing "-1": invalid syntax
注意:超出範圍時,回傳值是該寬度能表示的最大或最小值(上例的 127),同時回傳錯誤;一定要先檢查錯誤再使用值。數字中的底線
_ 只有在 base 為 0 時允許。ParseFloat
ParseFloat 把字串轉成浮點數,bitSize 填 32 或 64。接受一般小數、科學記號(1e3),以及 "Inf"、"NaN" 這些特殊值。簽名:
- func ParseFloat(s string, bitSize int) (float64, error)
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- for _, s := range []string{"3.14", "1e3", "-0.5", "inf", "abc"} {
- f, err := strconv.ParseFloat(s, 64)
- fmt.Println(f, err)
- }
- }
輸出:
- 3.14 <nil>
- 1000 <nil>
- -0.5 <nil>
- +Inf <nil>
- 0 strconv.ParseFloat: parsing "abc": invalid syntax
ParseBool 與 FormatBool
ParseBool 接受 1、t、T、TRUE、true、True 視為真,0、f、F、FALSE、false、False 視為假,其他字串都會回傳錯誤。FormatBool 回傳 "true" 或 "false"。簽名:
- func ParseBool(str string) (bool, error)
- func FormatBool(b bool) string
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- for _, s := range []string{"true", "1", "F", "yes"} {
- b, err := strconv.ParseBool(s)
- fmt.Println(b, err)
- }
- fmt.Println(strconv.FormatBool(true))
- }
輸出:
- true <nil>
- true <nil>
- false <nil>
- false strconv.ParseBool: parsing "yes": invalid syntax
- true
FormatInt
FormatInt 把 int64 轉成指定進位(2 到 36)的字串,超過 9 的位數用小寫字母表示。常用來輸出二進位、十六進位或短代碼。簽名:
- func FormatInt(i int64, base int) string
- func FormatUint(i uint64, base int) string
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- fmt.Println(strconv.FormatInt(255, 2))
- fmt.Println(strconv.FormatInt(255, 16))
- fmt.Println(strconv.FormatInt(-255, 16))
- fmt.Println(strconv.FormatInt(123456789, 36))
- }
輸出:
- 11111111
- ff
- -ff
- 21i3v9
FormatFloat
FormatFloat 把浮點數轉成字串,參數依序是:值、格式字元、精度、位元大小。| 格式 | 意思 |
|---|---|
'f' | 一般小數,如 3.14 |
'e' | 科學記號,如 3.14e+00 |
'g' | 自動選較短的那種 |
精度填 -1 代表「用能精確還原這個數字的最少位數」。這也會把浮點數的誤差如實呈現,例如
0.1 + 0.2 的結果並不剛好是 0.3(原因見 浮點數與複數);要顯示給人看時通常指定固定精度。簽名:
- func FormatFloat(f float64, fmt byte, prec, bitSize int) string
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- x := 1234.5678
- fmt.Println(strconv.FormatFloat(x, 'f', 2, 64))
- fmt.Println(strconv.FormatFloat(x, 'e', 3, 64))
- fmt.Println(strconv.FormatFloat(x, 'g', -1, 64))
- a, b := 0.1, 0.2
- fmt.Println(strconv.FormatFloat(a+b, 'f', -1, 64))
- fmt.Println(strconv.FormatFloat(a+b, 'f', 2, 64))
- }
輸出:
- 1234.57
- 1.235e+03
- 1234.5678
- 0.30000000000000004
- 0.30
Quote 與 Unquote
Quote 把字串包上雙引號,並把換行、Tab、控制字元等轉成跳脫序列(例如 \n),結果就是一個合法的 Go 字串字面值。Unquote 反過來解析帶引號的字串,也接受單引號字元與反引號原始字串。簽名:
- func Quote(s string) string
- func Unquote(s string) (string, error)
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- q := strconv.Quote("hi\tthere\n\"go\"")
- fmt.Println(q)
- s, err := strconv.Unquote(q)
- fmt.Println(s == "hi\tthere\n\"go\"", err)
- s, err = strconv.Unquote("`raw\\n`")
- fmt.Println(s, err)
- _, err = strconv.Unquote("no quotes")
- fmt.Println(err)
- }
輸出:
- "hi\tthere\n\"go\""
- true <nil>
- raw\n <nil>
- invalid syntax
AppendInt 與 AppendQuote
Append 系列把轉換結果直接接到 []byte 尾端並回傳,避免先產生中間字串。在需要重複使用緩衝區、大量輸出數字時使用,例如自己組 JSON 或日誌行。簽名:
- func AppendInt(dst []byte, i int64, base int) []byte
- func AppendQuote(dst []byte, s string) []byte
範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- func main() {
- buf := []byte(`{"id":`)
- buf = strconv.AppendInt(buf, 42, 10)
- buf = append(buf, `,"name":`...)
- buf = strconv.AppendQuote(buf, "Amy")
- buf = append(buf, '}')
- fmt.Println(string(buf))
- }
輸出:
- {"id":42,"name":"Amy"}
NumError、ErrSyntax 與 ErrRange
Parse 系列失敗時回傳 *NumError,裡面記錄呼叫的函式名稱(Func)、輸入字串(Num)與原因(Err)。原因通常是 ErrSyntax(格式不對)或 ErrRange(超出範圍),可以用 errors.Is 區分,給使用者不同的提示。錯誤檢查的方式見 errors。簽名:
- type NumError struct {
- Func string
- Num string
- Err error
- }
- var ErrRange = errors.New("value out of range")
- var ErrSyntax = errors.New("invalid syntax")
範例:
- package main
- import (
- "errors"
- "fmt"
- "strconv"
- )
- func parseAge(s string) (int, error) {
- n, err := strconv.ParseInt(s, 10, 8)
- switch {
- case errors.Is(err, strconv.ErrSyntax):
- return 0, fmt.Errorf("age %q is not a number", s)
- case errors.Is(err, strconv.ErrRange):
- return 0, fmt.Errorf("age %q is too large", s)
- }
- return int(n), nil
- }
- func main() {
- for _, s := range []string{"30", "thirty", "999"} {
- fmt.Println(parseAge(s))
- }
- }
輸出:
- 30 <nil>
- 0 age "thirty" is not a number
- 0 age "999" is too large
重點整理
Atoi/Itoa處理最常見的十進位int與字串互轉Parse系列會回傳錯誤,一定要檢查;Format系列不會失敗ParseInt的 base 為 0 時依0x、0b、0o字首自動判斷進位- 超出範圍時同時回傳極值與
ErrRange,先看錯誤再用值 - 數字轉字串不要用
string(n),那會得到字元而不是數字 Quote/Unquote處理帶跳脫字元的字串字面值