前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[go 标准库] strconv

[go 标准库] strconv

作者头像
柳公子
发布2021-05-06 11:51:56
8570
发布2021-05-06 11:51:56
举报
文章被收录于专栏:PhpZendo

[go 标准库] strconv

go strconv 包提供了基本数据类型与 string 类型相互转换常用的处理函数。提供了如下操作接口:

  • string 转其它基本数据类型
  • 其它数据类型转 string 数据类型
  • string、rune 的单引号与双引号包装、解包装
  • 基于以上操作接口的扩展功能

string 转其它基本数据类型

string 转其它数据类型的方法都是以 Parse 开头的函数包括:

  • ParseBool(str string) (bool, error) 字符转 bool
  • ParseComplex(s string, bitSize int) (complex128, error) 字符转 Complex
  • ParseFloat(s string, bitSize int) (float64, error) 字符转 Float
  • ParseInt(s string, base int, bitSize int) (int64, error) 字符转 Int
  • ParseUint(s string, base int, bitSize int) (uinit64, error) 字符转 Uint
  • 以及一个例外 Atoi(s string) (int, error) 功能类似 ParseInt(s, 10, 0),表示将 s 转换成十进制的 int 数据类型

Parse 函数族方法签名包括:待转换的字符串 s(str),指定转换目标类型的精度 bitSize,以及进行 Int(Uint) 型数据转换的进制 base

下面对这些函数进行具体说明:

ParseBool

ParseBool 是将字符串转换成 bool 类型,当传入

1, t, T, True, true, TRUE 等字符串时,返回值为 bool true 0, f, F, False, false, FALSE 等字符串时,返回值为 bool false 其它任何字符串将返回 error

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    v := "true"
    if s, err := strconv.ParseBool(v); err == nil {
        fmt.Printf("%T, %v\n", s, s)// bool, true
    }

    v = "tRue"
    if _, err := strconv.ParseBool(v); err != nil {
        fmt.Printf("ParseBool error: %v\n", err)// ParseBool error: strconv.ParseBool: parsing "tRue": invalid syntax
    }
}

ParseComplex

ParseComplex 是将字符串以给定的精度 bitSize 转换成 complex128 类型; 虽然 bitSize 取值可为 64(complex64) | 128(complex128),但最终返回结果都是 complex128 类型,当 bitSize = 64 时,会在方法内部将值 complex128 转成 complex64 而不改变其值。

ParseFloat

ParseFloat 是将字符串以给定的精度 bitSize 转换成 float64 类型; 虽然 bitSize 取值可为 32 (float32)| 64(float64),但最终返回结果都是 float64 类型,当 bitSize = 32 时,会在方法内部将值 float64 转成 float32 而不改变其值。

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    v := "3.1415926535"
    if s, err := strconv.ParseFloat(v, 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)// float64, 3.1415927410125732
    }
    if s, err := strconv.ParseFloat(v, 64); err == nil {
        fmt.Printf("%T, %v\n", s, s)// float64, 3.1415926535
    }
    if s, err := strconv.ParseFloat("NaN", 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)// float64, NaN
    }
    // ParseFloat is case insensitive
    if s, err := strconv.ParseFloat("nan", 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)// float64, NaN
    }
    if s, err := strconv.ParseFloat("inf", 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)//float64, +Inf
    }
    if s, err := strconv.ParseFloat("+Inf", 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)//float64, +Inf
    }
    if s, err := strconv.ParseFloat("-Inf", 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)//float64, -Inf
    }
    if s, err := strconv.ParseFloat("-0", 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)//float64, -0
    }
    if s, err := strconv.ParseFloat("+0", 32); err == nil {
        fmt.Printf("%T, %v\n", s, s)//float64, 0
    }
}

ParseInt & Atoi

ParseInt 是将字符串以给定的进制 base 和精度 bitSize 转换成 int64 类型;

base 进制取值范围为 [0, 36],bitSize 取值为 [0, 64]。但是当 base 取 0 时,方法依据待转换字符串 s 的前导 0 来解析实际的实际需要转化进制,解析规则如下:

  • 0b 解析成二进制
  • 0 或 0o 解析成八进制
  • 0x 解析成十六进制
  • 否则为 10 进制

bitSize 进度取值一般为 0(int), 8(int8), 16(int16), 32(int32), 64(int64)

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    v32 := "-354634382"
    if s, err := strconv.ParseInt(v32, 0, 32); err == nil {
        fmt.Printf("base10: %T, %v\n", s, s)// base10: int64, -354634382
    }
    if s, err := strconv.ParseInt(v32, 16, 32); err == nil {
        fmt.Printf("base16:%T, %v\n", s, s)
    } 

    v64 := "-3546343826724305832"
    if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
        fmt.Printf("%T, %v\n", s, s)// int64, -3546343826724305832
    }
    if s, err := strconv.ParseInt(v64, 16, 64); err == nil {
        fmt.Printf("%T, %v\n", s, s)
    }
}

ParseUint

功能类似 ParseInt,只是转成无符号整型

其它数据类型转 string 数据类型

其它数据类型 转string 类型的方法都是以 Format 开头的函数包括:

  • FormatBool(b bool) string bool 转字符串
  • FormatComplex(c complex128, fmt byte, prec, bitSize int) string Complex 转字符串
  • FormatFloat(f float64, fmt byte, prec, bitSize int) string Float转字符串
  • FormatInt(i int64, base int) string Int 转字符串
  • FormatUint(i uint64, base int) string Uint 转字符串
  • 以及一个例外 Itoa(i int) string 功能类似 FormatInt(int64(i), 10),表示将 int i 转换成字符串

Format 函数族方法签名包括:待转换的数据 bool | complex128 | float64 | int64 | uint64, complex128 | float64 指定转换目标类型的格式 fmt, 保留小数位 prec 和 精度 bitSize;以及进行 int(uint) 型数据转换的进制 base

FormatBool

FormatBool 依据 bool 值 b 转成 "true" 或 "false" 字符串

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    v := true
    s := strconv.FormatBool(v)
    fmt.Printf("%T, %v\n", s, s)// string, true

}

FormatComplex

FormatComplex 将 complex 复数转成 (a+bi) 格式的字符串,a 和 b 分别为实数和虚数部分。

参数 fmt, prec, bitSize 含义同 FormatFloat,需要注意的是 bitSize 取值仅为 64 或 128。

FormatFloat

FormatFloat 将浮点数依据给定的格式 fmt 和精度 prec 转换成字符串。同时它会根绝给定的 bitSize 位数(32 为 float32,64 为 float64)对小数部分进行四舍五入。

格式化参数 fmt 取值如下:

  • b 二进制: -ddddp±ddd
  • e 科学计数: -d.dddde±dd
  • E 科学计数: -d.ddddE±dd
  • f 无进制指数: -ddd.dddd
  • g 'e' 大指数, 'f' 的其它情况
  • G 'E' 大指数, 'f' 的其它情况
  • x 十六进制分数和二进制指数: -0xd.ddddp±ddd
  • X 十六进制分数和二进制指数: -0Xd.ddddP±ddd
代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    v := 3.1415926535

    s32 := strconv.FormatFloat(v, 'E', -1, 32)
    fmt.Printf("%T, %v\n", s32, s32)// string, 3.1415927E+00

    s64 := strconv.FormatFloat(v, 'E', -1, 64)
    fmt.Printf("%T, %v\n", s64, s64)// string, 3.1415926535E+00
}

FormatInt

FormatInt 将给定整数 i 以给定的的进制 base (2<= base <= 36)转换成字符串

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    v := int64(-42)

    s10 := strconv.FormatInt(v, 10)
    fmt.Printf("%T, %v\n", s10, s10)// string, -42

    s16 := strconv.FormatInt(v, 16)
    fmt.Printf("%T, %v\n", s16, s16)//string, -2a

}

FormatUint

功能同 FormatInt,用于转换无符号整型数据

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    v := uint64(42)

    s10 := strconv.FormatUint(v, 10)
    fmt.Printf("%T, %v\n", s10, s10)// string, 42

    s16 := strconv.FormatUint(v, 16)
    fmt.Printf("%T, %v\n", s16, s16)// string, 2a

}

Format 函数族的一些扩展函数如下:

  • AppendBool(dst []byte, b bool) []byte
  • AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte
  • AppendInt(dst []byte, i int64, base int) []byte
  • AppendUint(dst []byte, i uint64, base int) []byte

功能是将 bool, float64, int64 uint64 数据转成字符串并追接到字节 dst 中返回 []byte。函数签名中除 dst 外的其它形参同对应的 Format 函数。

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    b10 := []byte("int (base 10):")
    b10 = strconv.AppendInt(b10, -42, 10)
    fmt.Println(b10, string(b10))// [105 110 116 32 40 98 97 115 101 32 49 48 41 58 45 52 50] int (base 10):-42

    b16 := []byte("int (base 16):")
    b16 = strconv.AppendInt(b16, -42, 16)
    fmt.Println(b16, string(b16))// [105 110 116 32 40 98 97 115 101 32 49 54 41 58 45 50 97] int (base 16):-2a
}

string、rune 的单引号与双引号包装、解包装

string、rune 的单引号与双引号包装的方法都是以 Quote 开头的函数包括:

  • Quote(s string) string 将字符串 s 以双引号包装
  • QuoteToASCII(s string) string 将字符串 s 以双引号包装并转成 ASCII 码
  • QuoteToGraphic(s string) string 将字符串 s 以双引号包装并转成字符文字
  • QuoteRune(r rune) string 将 rune 以双引号包装
  • QuoteRuneToASCII(r rune) string 将 rune 以单引号包装并转成 ASCII 码
  • QuoteRuneToGraphic(r rune) string 将 rune 以单引号包装并转成字符文字
  • Unquote(s string) (string, error) 将单引号、双引号及反引号包装的字符串解包装
  • UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)

下面对这些函数进行具体说明:

Quote

Quote 将字符串 s 以双引号包装成新字符返回。返回的字符会对控制字符和 IsPrint 方法中定义的不可打印字符进行转义。

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    // This string literal contains a tab character.
    s := strconv.Quote(`"Fran & Freddie's Diner ☺"`)
    fmt.Println(s)// "\"Fran & Freddie's Diner\t☺\""
}

QuoteToASCII

QuoteToASCII 方法功能同 Quote 方法,不过会将非 ASCII 码、不可打印字符进行转义

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    // This string literal contains a tab character.
    s := strconv.QuoteToASCII(`"Fran & Freddie's Diner  ☺"`)
    fmt.Println(s)// "\"Fran & Freddie's Diner\t\u263a\""

}

QuoteToGraphic

QuoteToGraphic 方法功能同 Quote 方法,不过会将非图文字符专业

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    s := strconv.QuoteToGraphic("☺")
    fmt.Println(s)// "☺"

    // This string literal contains a tab character.
    s = strconv.QuoteToGraphic("This is a \u263a    \u000a")
    fmt.Println(s)// "This is a ☺\t\n"

    s = strconv.QuoteToGraphic(`" This is a ☺ \n "`)
    fmt.Println(s)// "\" This is a ☺ \\n \""

}

QuoteRune 函数族同 Quote 功能类似,这里不再赘述。

Unquote

Unquote 会将待单引号、双引号和反引号的字符串或字符进行引号截取。

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    s, err := strconv.Unquote("You can't unquote a string without quotes")
    fmt.Printf("%q, %v\n", s, err) // "", invalid syntax
    s, err = strconv.Unquote("\"The string must be either double-quoted\"")
    fmt.Printf("%q, %v\n", s, err) // "The string must be either double-quoted", <nil>
    s, err = strconv.Unquote("`or backquoted.`")
    fmt.Printf("%q, %v\n", s, err) // "or backquoted.", <nil>
    s, err = strconv.Unquote("'\u263a'") // single character only allowed in single quotes
    fmt.Printf("%q, %v\n", s, err) // "☺", <nil>
    s, err = strconv.Unquote("'\u2639\u2639'")
    fmt.Printf("%q, %v\n", s, err) // "", invalid syntax

}

Quote 函数族的一些扩展函数如下:

  • AppendQuote(dst []byte, s string) []byte
  • AppendQuoteToASCII(dst []byte, s string) []byte
  • AppendQuoteToGraphic(dst []byte, s string) []byte
  • AppendQuoteRune(dst []byte, r rune) []byte
  • AppendQuoteRuneToASCII(dst []byte, r rune) []byte
  • AppendQuoteRuneToGraphic(dst []byte, r rune) []byte

AppendQuoteXXX 函数同 Quote 类似会将字符或字符串用单(双)引号包装并追加到 []byte 字节切片返回

代码语言:javascript
复制
package main

import (
    "fmt"
    "strconv"
)

func main() {
    b := []byte("quote:")
    b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)
    fmt.Println(string(b))// [113 117 111 116 101 58 34 92 34 70 114 97 110 32 38 32 70 114 101 100 100 105 101 39 115 32 68 105 110 101 114 92 34 34] quote:"\"Fran & Freddie's Diner\""
}

附上整理的思维导图

参考资料

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年4月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • [go 标准库] strconv
    • string 转其它基本数据类型
      • ParseBool
      • ParseComplex
      • ParseFloat
      • ParseInt & Atoi
      • ParseUint
    • 其它数据类型转 string 数据类型
      • FormatBool
      • FormatComplex
      • FormatFloat
      • FormatInt
      • FormatUint
    • string、rune 的单引号与双引号包装、解包装
      • Quote
      • QuoteToASCII
      • QuoteToGraphic
    • Unquote
      • 参考资料
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档