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}))// Hello3 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 := 10s := strconv.Itoa(i)fmt.Printf("%T, %v\n", s, s)// string, 10strconv.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.1415927410125732if s, err := strconv.ParseFloat(v, 64); err == nil { fmt.Printf("%T, %v\n", s, s)}// float64, 3.1415926535strconv.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, -354634382v64 := "-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, -3546343826724305832strconv.FormatFloat(f float64, fmt byte, prec, bitSize int) string

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

v := 3.1415926535s32 := strconv.FormatFloat(v, 'E', -1, 32)fmt.Printf("%T, %v\n", s32, s32)// string, 3.1415927E+00s64 := strconv.FormatFloat(v, 'E', -1, 64)fmt.Printf("%T, %v\n", s64, s64)// string, 3.1415926535E+00strconv.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, -42s16 := strconv.FormatInt(v, 16)fmt.Printf("%T, %v\n", s16, s16)// string, -2astrconv.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+00b64 := []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):-42b16 := []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):42b16 := []byte("uint (base 16):")b16 = strconv.AppendUint(b16, 42, 16)fmt.Println(string(b16))// uint (base 16):2astrconv.CanBackquote(s string) bool

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

fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))// truefmt.Println(strconv.CanBackquote("`can't backquote this`"))// falsestrconv.FormatBool(b bool) string

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

v := trues := strconv.FormatBool(v)fmt.Printf("%T, %v\n", s, s)// string, truestrconv.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, 42s16 := strconv.FormatUint(v, 16)fmt.Printf("%T, %v\n", s16, s16)// string, 2astrconv.IsPrint(r rune) bool

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

c := strconv.IsPrint('\u263a')fmt.Println(c)// truebel := strconv.IsPrint('\007')fmt.Println(bel)// falsestrconv.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, truestrconv.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, 42if s, err := strconv.ParseUint(v, 10, 64); err == nil { fmt.Printf("%T, %v\n", s, s)}// uint64, 42strconv.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 syntaxs, 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 quotesfmt.Printf("%q, %v\n", s, err)// "☺", <nil>s, err = strconv.Unquote("'\u2639\u2639'")fmt.Printf("%q, %v\n", s, err)// "", invalid syntaxstrconv.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: falsefmt.Println("tail:", t)// tail: Fran & Freddie's Diner\"

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