Go语言中其他数据与字符串类型的转换

1 概述

Go语言是强类型语言,因此总会需要将字符串转成需要的类型。比如整型和字符串转换,字符串和布尔型的转换等。本文就介绍如何完成这些转换,以下是Go语言关于字符串转换的整理说明,主要是与切片类型的转换,和 strconv 包的使用。

2 与切片的转换

切片类型可以和字符串类型相互转换。

fmt.Println([]rune("Hello小韩说课"))
// [72 101 108 108 111 23567 38889 35828 35838]
fmt.Println(string([]rune{72, 101, 108, 108, 111, 23567, 38889, 35828, 35838}))
// Hello小韩说课

fmt.Println([]byte("Hello"))
// [72 101 108 108 111]
fmt.Println(string([]byte{72, 101, 108, 108, 111}))
// Hello

3 strconv 包

会将常用的放在前面:

strconv.Atoi(s string) (int, error)

转换字符串 s string 到整型。

v := "10"
if s, err := strconv.Atoi(v); err == nil {
    fmt.Printf("%T, %v", s, s)
}
// int, 10

// 相当于
strconv.ParseInt(s, 10, 0)

strconv.Itoa(i int) string

将整型转 i int 换为字符串

i := 10
s := strconv.Itoa(i)
fmt.Printf("%T, %v\n", s, s)
// string, 10

strconv.ParseFloat(s string, bitSize int) (float64, error)

解析字符 str string 串为浮点,可以设置位数。

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

strconv.ParseInt(s string, base int, bitSize int) (i int64, err error)

解析字符 str string 串为整数,可以设置进制、位数。

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

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

strconv.FormatFloat(f float64, fmt byte, prec, bitSize int) string

将浮点数 f float64 转换为字符串,可以设置格式 fmt(b,e,E,f,g,G)、精度prce、位数(32或64)。

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

strconv.FormatInt(i int64, base int) string

将整数 i int64 转换为字符串,可以指定进制 base。

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

strconv.AppendBool(dst []byte, b bool) []byte

将布尔值 b bool 以字符串形式追加到 dst []byte 中。

b := []byte("bool:")
b = strconv.AppendBool(b, true)
fmt.Println(string(b))
// bool:true

// 相当于
append(dst []byte, strconv.FormatBool(b bool))

strconv.AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte

将浮点数 f float64 以字符串形式追加到 dst []byte 中,可以设置格式 fmt(b,e,E,f,g,G)、精度prce、位数(32或64)。

b32 := []byte("float32:")
b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
fmt.Println(string(b32))
// float32:3.1415927E+00

b64 := []byte("float64:")
b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
fmt.Println(string(b64))
// float64:3.1415926535E+00

// 相当于
append(dst []byte, strconv.FormatFloat(3.1415926535, 'E', -1, 64))

strconv.AppendInt(dst []byte, i int64, base int) []byte

将整数 i int64 以字符串形式追加到 dst []byte 中,可以指定进制。

b10 := []byte("int (base 10):")
b10 = strconv.AppendInt(b10, -42, 10)
fmt.Println(string(b10))
// int (base 10):-42

b16 := []byte("int (base 16):")
b16 = strconv.AppendInt(b16, -42, 16)
fmt.Println(string(b16))
// int (base 16):-2a

// 相当于
append(dst []byte, strconv.FormatInt(-42, 10))
append(dst []byte, strconv.FormatInt(-42, 16))

strconv.AppendQuote(dst []byte, s string) []byte

将字符串 s string 以字符串双引号定义的形式追加到 dst []byte 中。

b := []byte("quote:")
b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)
fmt.Println(string(b))
// quote:"\"Fran & Freddie's Diner\""

// 相当于
append(dst []byte, strconv.Quote(`"Fran & Freddie's Diner"`))

strconv.AppendQuoteRune(dst []byte, r rune) []byte

将字符 r rune 以字单引号定义的形式追加到 dst []byte 中。

b := []byte("rune:")
b = strconv.AppendQuoteRune(b, '☺')
fmt.Println(string(b))
// rune:'☺'

// 相当于
append(dst []byte, strconv.QuoteRune('☺'))

strconv.AppendQuoteRuneToASCII(dst []byte, r rune) []byte

将字符 r rune 以字单引号定义的形式追加到 dst []byte 中,对于非 ASCII 字符 r 会以转义字符的形式出现。

b := []byte("rune (ascii):")
b = strconv.AppendQuoteRuneToASCII(b, '☺')
fmt.Println(string(b))
// rune (ascii):'\u263a'

// 相当于
append(dst []byte, strconv.QuoteRuneToASCII('☺'))

strconv.AppendQuoteToASCII(dst []byte, s string) []byte

将字符串 s string 以字符串双引号定义的形式追加到 dst []byte 中,非 ASCII 字符以转义形式表示。

b := []byte("quote (ascii):")
b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)
fmt.Println(string(b))
// quote (ascii):"\"Fran & Freddie's Diner\""

// 相当于
append(dst []byte, strconv.QuoteToASCII(`"Fran & Freddie's Diner"`))

strconv.AppendUint(dst []byte, i uint64, base int) []byte

将无符号整数 i uint64 以字符串形式追加到 dst []byte 中,可以指定进制。

b10 := []byte("uint (base 10):")
b10 = strconv.AppendUint(b10, 42, 10)
fmt.Println(string(b10))
// uint (base 10):42

b16 := []byte("uint (base 16):")
b16 = strconv.AppendUint(b16, 42, 16)
fmt.Println(string(b16))
// uint (base 16):2a

strconv.CanBackquote(s string) bool

检测字符串 s string 是否可以不被修改的表示为一个单行的、没有空格和tab之外控制字符的反引号字符串。

fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))
// true
fmt.Println(strconv.CanBackquote("`can't backquote this`"))
// false

strconv.FormatBool(b bool) string

将布尔 b bool 转换为字符串。

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

strconv.FormatUint(i uint64, base int) string

将无符号整数 i uint64 转换为字符串,可以指定进制 base。

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

strconv.IsPrint(r rune) bool

检测字符 r rune 是否为打印字符。

c := strconv.IsPrint('\u263a')
fmt.Println(c)
// true

bel := strconv.IsPrint('\007')
fmt.Println(bel)
// false

strconv.ParseBool(str string) (bool, error)

解析字符 str string 串为布尔型。

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

strconv.ParseUint(s string, base int, bitSize int) (uint64, error)

解析字符 str string 串为无符号整数,可以设置进制、位数。

v := "42"
if s, err := strconv.ParseUint(v, 10, 32); err == nil {
    fmt.Printf("%T, %v\n", s, s)
}
// uint64, 42
if s, err := strconv.ParseUint(v, 10, 64); err == nil {
    fmt.Printf("%T, %v\n", s, s)
}
// uint64, 42

strconv.Quote(s string) string

返回字符串 s string 双引号字面值表示,控制字符、不可打印字符会进行转义,如 \t,\n,\xFF,\u0100。

s := strconv.Quote(`"Fran & Freddie's Diner ☺"`)
fmt.Println(s)
// "\"Fran & Freddie's Diner\t☺\""

strconv.QuoteRune(r rune) string

返回字符 r rune 单引号字面值表示,控制字符、不可打印字符会进行转义,如\t,\n,\xFF,\u0100。

s := strconv.QuoteRune('☺')
fmt.Println(s)
// '☺'

strconv.QuoteRuneToASCII(r rune) string

返回字符 r rune 单引号字面值表示,控制字符、不可打印字符、非ASCII字符会进行转义。

s := strconv.QuoteRuneToASCII('☺')
fmt.Println(s)
// '\u263a'

strconv.QuoteToASCII(s string) string

返回字符串 s string 双引号字面值表示,控制字符和不可打印字符、非ASCII字符会进行转义。

s := strconv.QuoteToASCII(`"Fran & Freddie's Diner  ☺"`)
fmt.Println(s)
// "\"Fran & Freddie's Diner\t\u263a\""

strconv.Unquote(s string) (string, error)

返回一个单引号、双引号、反引号包围的语法字符串 s string,解析它并返回它表示的值。若为反引号括起来的,函数会认为s是go字符字面值,返回一个单字符的字符串。

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

strconv.UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)

返回一个表示字符的语法字符串 s string,可以设置字符串定义语法 quote byte 双引号或者反引号。解析它并返回四个值:

v, mb, t, err := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')
if err != nil {
    log.Fatal(err)
}

fmt.Println("value:", string(v))
// value: "
fmt.Println("multibyte:", mb)
// multibyte: false
fmt.Println("tail:", t)
// tail: Fran & Freddie's Diner\"

完!
原文出自:小韩说课
微信关注:小韩说课
小韩说课

转载于:https://blog.51cto.com/2980679/2309827

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值