导入strconv包
Append
Format
Parse
字符串转其他类型
parse返回两个值,一个转换值,一个err,没有错误时,err返回的是nil,有错误,err接受错误信息。
整型转字符串
Itoa
字符串转整型
a=567
//
a:=strconv.FormatFloat(10.100,'f',-1,32)
输出:
10.1
a := strconv.FormatFloat(10.101, 'f', -1, 64)
输出:
10.101
a := strconv.FormatFloat(10.010, 'f', -1, 64)
输出:10.01
a:=strconv.FormatFloat(10.1,'f',2,64)
输出:10.10
f 参数可以时e,E,g,G
-1 代表输出的精度小数点后的位数,如果是<0的值,则返回最少的位数来表示该数,如果是大于0的则返回对应位数的值
64 为float的类型,go中float分为32和64位,因此就需要传入32或者64
//
golang strconv.ParseInt 是将字符串转换为数字的函数,功能灰常之强大,看的我口水直流.
func ParseInt(s string, base int, bitSize int) (i int64, err error)
参数1 数字的字符串形式
参数2 数字字符串的进制 比如二进制 八进制 十进制 十六进制
参数3 返回结果的bit大小 也就是int8 int16 int32 int64
代码:
01package main
02
03import (
04 "strconv"
05)
06
07func main() {
08 i, err := strconv.ParseInt("123", 10, 32)
09 if err != nil {
10 panic(err)
11 }
12 println(i)
13}
离家已近一载,虽偶有思乡欲踏归途之心,但奈何各种各样现实原因的羁绊,始终未能如愿动身,或许下一次的归途似乎只能安排到下一个收获的黄金时节。说起家乡对于大多数人而言总感觉是一个神秘的地方,在的时候总想着逃离,离开时候总想着回归,果然人类的悲欢离合总是那么的惊奇。
go语言的strconv包主要提供了一些不同数据类型相互转化的函数和方法,下面将针对这些函数方法展开讲解。
package main
/*********************************************************************/
/**************** golang中strconv包相关API讲解 *********************/
/********************************************************************/
/*
Constants
Variables
func AppendBool(dst []byte, b bool) []byte
func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte
func AppendInt(dst []byte, i int64, base int) []byte
func AppendQuote(dst []byte, s string) []byte
func AppendQuoteRune(dst []byte, r rune) []byte
func AppendQuoteRuneToASCII(dst []byte, r rune) []byte
func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte
func AppendQuoteToASCII(dst []byte, s string) []byte
func AppendQuoteToGraphic(dst []byte, s string) []byte
func AppendUint(dst []byte, i uint64, base int) []byte
func Atoi(s string) (int, error)
func CanBackquote(s string) bool
func FormatBool(b bool) string
func FormatComplex(c complex128, fmt byte, prec, bitSize int) string
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
func FormatInt(i int64, base int) string
func FormatUint(i uint64, base int) string
func IsGraphic(r rune) bool
func IsPrint(r rune) bool
func Itoa(i int) string
func ParseBool(str string) (bool, error)
func ParseComplex(s string, bitSize int) (complex128, error)
func ParseFloat(s string, bitSize int) (float64, error)
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (uint64, error)
func Quote(s string) string
func QuoteRune(r rune) string
func QuoteRuneToASCII(r rune) string
func QuoteRuneToGraphic(r rune) string
func QuoteToASCII(s string) string
func QuoteToGraphic(s string) string
func Unquote(s string) (string, error)
func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
type NumError
func (e *NumError) Error() string
func (e *NumError) Unwrap() error
*/
func main() {
/**
*AppendBool根据b的值将"true"或"false"附加到dst并返回扩展缓冲区。
*func AppendBool(dst []byte, b bool) []byte
*/
/*
b := []byte("bool:")
b = strconv.AppendBool(b, true)
fmt.Println(string(b))
*/
/**
*AppendFloat将由FormatFloat生成的浮点数f的字符串形式附加到dst,并返回扩展缓冲区。
*func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte
*/
/*
b32 := []byte("float32:")
b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
fmt.Println(string(b32))
b64 := []byte("float64:")
b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
fmt.Println(string(b64))
*/
/**
*AppendInt将由FormatInt生成的整数i的字符串形式附加到dst,并返回扩展缓冲区。
*func AppendInt(dst []byte, i int64, base int) []byte
*/
/*
b10 := []byte("int (base 10):")
b10 = strconv.AppendInt(b10, -42, 10)
fmt.Println(string(b10))
b16 := []byte("int (base 16):")
b16 = strconv.AppendInt(b16, -42, 16)
fmt.Println(string(b16))
*/
/**
*AppendQuote将由Quote生成的表示s的double-quoted Go字符串文字附加到dst,
*并返回扩展缓冲区。
*func AppendQuote(dst []byte, s string) []byte
*/
/*
b := []byte("quote:")
b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)
fmt.Println(string(b))
*/
/**
*AppendQuoteRune将由QuoteRune生成的代表符文的single-quoted Go字符文字附加到dst,
*并返回扩展缓冲区。
*func AppendQuoteRune(dst []byte, r rune) []byte
*/
/*
b := []byte("rune:")
b = strconv.AppendQuoteRune(b, '☺')
fmt.Println(string(b))
*/
/**
*AppendQuoteToASCII将QuoteToASCII生成的表示s的double-quoted Go字符串文字附加到dst,
*并返回扩展缓冲区。
*func AppendQuoteRuneToASCII(dst []byte, r rune) []byte
*/
/*
b := []byte("quote (ascii):")
b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)
fmt.Println(string(b))
*/
/**
*QuoteToGraphic返回代表s的double-quoted Go字符串文字。返回的字符串保留IsGraphic定义的
*Unicode图形字符不变,并且对非图形字符使用Go转义序列(\ t,\ n,\ xFF,\ u0100)。
*func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte
*/
/*
s := strconv.QuoteToGraphic("☺")
fmt.Println(s)
s = strconv.QuoteToGraphic("This is a \u263a \u000a")
fmt.Println(s)
s = strconv.QuoteToGraphic(`" This is a ☺ \n "`)
fmt.Println(s)
*/
/**
*AppendQuoteToASCII将QuoteToASCII生成的表示s的double-quoted Go字符串文字附加到dst,
*并返回扩展缓冲区。
*func AppendQuoteToASCII(dst []byte, s string) []byte
*/
/*
b := []byte("quote (ascii):")
b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)
fmt.Println(string(b))
*/
/**
*
*func AppendQuoteToGraphic(dst []byte, s string) []byte
*/
/**
*AppendUint将由FormatUint生成的无符号整数i的字符串形式附加到dst,然后返回扩展缓冲区。
*func AppendUint(dst []byte, i uint64, base int) []byte
*/
/*
b10 := []byte("uint (base 10):")
b10 = strconv.AppendUint(b10, 42, 10)
fmt.Println(string(b10))
b16 := []byte("uint (base 16):")
b16 = strconv.AppendUint(b16, 42, 16)
fmt.Println(string(b16))
*/
/**
*AppendUint将由FormatUint生成的无符号整数i的字符串形式附加到dst,然后返回扩展缓冲区。
*func Atoi(s string) (int, error)
*/
/*
v := "10"
if s, err := strconv.Atoi(v); err == nil {
fmt.Printf("%T, %v", s, s)
}
*/
/**
*CanBackquote报告字符串s是否可以不变地表示为单行反引号字符串,并且没有制表符以外的控制字符。
*func CanBackquote(s string) bool
*/
/*
fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))
fmt.Println(strconv.CanBackquote("`can't backquote this`"))
*/
/**
*FormatBool根据b的值返回"true"或"false"。
*func FormatBool(b bool) string
*/
/*
v := true
s := strconv.FormatBool(v)
fmt.Printf("%T, %v\n", s, s)
*/
/**
*
*func FormatComplex(c complex128, fmt byte, prec, bitSize int) string
*/
/**
*根据设定的进度转换为指定的float类型
*func FormatFloat(f float64, fmt byte, prec, bitSize int) string
*/
/*
v := 3.1415926535
s32 := strconv.FormatFloat(v, 'E', -1, 32)
fmt.Printf("%T, %v\n", s32, s32)
s64 := strconv.FormatFloat(v, 'E', -1, 64)
fmt.Printf("%T, %v\n", s64, s64)
*/
/**
*FormatInt以2 <= base <= 36的形式返回给定基数i的字符串表示形式。
*结果使用小写字母'a'到'z'表示数字值> = 10。
*func FormatInt(i int64, base int) string
*/
/*
v := int64(-42)
s10 := strconv.FormatInt(v, 10)
fmt.Printf("%T, %v\n", s10, s10)
s16 := strconv.FormatInt(v, 16)
fmt.Printf("%T, %v\n", s16, s16)
*/
/**
*IsGraphic报告是否通过Unicode将符文定义为图形。此类字符包括字母,标记,
*数字,标点符号,符号和空格,来自类别L,M,N,P,S和Zs。
*func IsGraphic(r rune) bool
*/
/*
shamrock := strconv.IsGraphic('☘')
fmt.Println(shamrock)
a := strconv.IsGraphic('a')
fmt.Println(a)
bel := strconv.IsGraphic('\007')
fmt.Println(bel)
*/
/**
*IsPrint报告符文是否已定义为Go可打印的符文,其定义与unicode.IsPrint:
*字母,数字,标点,符号和ASCII空间。
*func IsPrint(r rune) bool
*/
/*
c := strconv.IsPrint('\u263a')
fmt.Println(c)
bel := strconv.IsPrint('\007')
fmt.Println(bel)
*/
/**
*Itoa等效于FormatInt(int64(i),10)。
*func Itoa(i int) string
*/
/*
i := 10
s := strconv.Itoa(i)
fmt.Printf("%T, %v\n", s, s)
*/
/**
*ParseBool返回由字符串表示的布尔值。它接受1,t,T,TRUE,true,True,0,f,F,FALSE,
*false,False。其他任何值都将返回错误。
*func ParseBool(str string) (bool, error)
*/
/*
v := "true"
if s, err := strconv.ParseBool(v); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
*/
/**
*
*func ParseComplex(s string, bitSize int) (complex128, error)
*/
/**
*ParseFloat将字符串s转换为由bitSize指定的精度的浮点数
*func ParseFloat(s string, bitSize int) (float64, error)
*/
/*
v := "3.1415926535"
if s, err := strconv.ParseFloat(v, 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat(v, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("NaN", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("nan", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("inf", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("+Inf", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("-Inf", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("-0", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("+0", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
*/
/**
*ParseInt解析给定基数(0、2到36)和位大小(0到64)中的字符串s,并返回相应的值i。
*func ParseInt(s string, base int, bitSize int) (i int64, err error)
*/
/*
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)
}
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)
}
*/
/**
*ParseUint类似于ParseInt,但用于无符号数字。
*func ParseUint(s string, base int, bitSize int) (uint64, error)
*/
/*
v := "42"
if s, err := strconv.ParseUint(v, 10, 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseUint(v, 10, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
*/
/**
*引用返回一个表示s的double-quoted Go字符串文字。返回的字符串使用Go转义序列
*(\ t,\ n,\ xFF,\ u0100)来控制字符和IsPrint定义的不可打印字符。
*func Quote(s string) string
*/
/*
s := strconv.Quote(`"Fran & Freddie's Diner ☺"`)
fmt.Println(s)
*/
/**
*QuoteRune返回代表符文的single-quoted Go字符文字。返回的字符串使用Go转义序列
*(\ t,\ n,\ xFF,\ u0100)来控制字符和IsPrint定义的不可打印字符。
*func QuoteRune(r rune) string
*/
/*
s := strconv.QuoteRune('☺')
fmt.Println(s)
*/
/**
*QuoteRuneToASCII返回代表符文的single-quoted Go字符文字。返回的字符串对IsASCII
*定义的非ASCII字符和不可打印的字符使用Go转义序列(\ t,\ n,\ xFF,\ u0100)。
*func QuoteRuneToASCII(r rune) string
*/
/*
s := strconv.QuoteRuneToASCII('☺')
fmt.Println(s)
*/
/**
*QuoteRuneToGraphic返回代表符文的single-quoted Go字符文字。如果符文不是IsGraphic
*定义的Unicode图形字符,则返回的字符串将使用Go转义序列(\ t,\ n,\ xFF,\ u0100)。
*func QuoteRuneToGraphic(r rune) string
*/
/*
s := strconv.QuoteRuneToGraphic('☺')
fmt.Println(s)
s = strconv.QuoteRuneToGraphic('\u263a')
fmt.Println(s)
s = strconv.QuoteRuneToGraphic('\u000a')
fmt.Println(s)
s = strconv.QuoteRuneToGraphic(' ') // tab character
fmt.Println(s)
*/
/**
*QuoteToASCII返回代表s的double-quoted Go字符串文字。返回的字符串对
*IsASCII定义的非ASCII字符和不可打印的字符使用Go转义序列(\ t,\ n,\ xFF,\ u0100)。
*func QuoteToASCII(s string) string
*/
/*
s := strconv.QuoteToASCII(`"Fran & Freddie's Diner ☺"`)
fmt.Println(s)
*/
/**
*QuoteToGraphic返回代表s的double-quoted Go字符串文字。返回的字符串保留IsGraphic定义
*的Unicode图形字符不变,并且对非图形字符使用Go转义序列(\ t,\ n,\ xFF,\ u0100)。
*func QuoteToGraphic(s string) string
*/
/*
s := strconv.QuoteToGraphic("☺")
fmt.Println(s)
s = strconv.QuoteToGraphic("This is a \u263a \u000a")
fmt.Println(s)
s = strconv.QuoteToGraphic(`" This is a ☺ \n "`)
fmt.Println(s)
*/
/**
*Unquote将s解释为single-quoted,double-quoted或带反引号的Go字符串文字,
*并返回用s引起引用的字符串值。
*(如果s是single-quoted,则它将是Go字符文字; Unquote返回相应的one-character字符串。)
*func Unquote(s string) (string, error)
*/
/*
s, err := strconv.Unquote("You can't unquote a string without quotes")
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("\"The string must be either double-quoted\"")
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("`or backquoted.`")
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("'\u263a'") // single character only allowed in single quotes
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("'\u2639\u2639'")
fmt.Printf("%q, %v\n", s, err)
*/
/**
*UnquoteChar解码转义的字符串或由字符串s表示的字符文字中的第一个字符或字节。
*它返回四个值
*func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
*/
/*
v, mb, t, err := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')
if err != nil {
log.Fatal(err)
}
fmt.Println("value:", string(v))
fmt.Println("multibyte:", mb)
fmt.Println("tail:", t)
*/
/**********************************************************************/
/**************** NumError中相关方法讲解 ***************************/
/********************************************************************/
/**
*NumError记录转换失败
*func (e *NumError) Error() string
*/
/*
str := "Not a number"
if _, err := strconv.ParseFloat(str, 64); err != nil {
e := err.(*strconv.NumError)
fmt.Println("Func:", e.Func)
fmt.Println("Num:", e.Num)
fmt.Println("Err:", e.Err)
fmt.Println(err)
}
*/
/**
*使用 Unwrap 方法可以获取一个错误中包含的另外一个错误
*func (e *NumError) Unwrap() error
*/
}
strconv这部分的内容讲解的内容虽然很多,但是实际上常用的转换的类型也就是几种,从实际的掌握难度上来讲应该不是非常的困难,因此这个部分的内容还是强力建议必须拿下来。
Golang的strconv
包主要实现字符串和基本数据类型之间的转换
字符串转换过程中可能出错,strconv
包定义了两个error
类型的变量,分别是ErrRange
和ErrSyntax
。
ErrRange
表示值超过类型能表示的最大范围,比如将字符串"128"转换为int8
会发生ErrRange
错误。var ErrRange = errors.New("value out of range")
ErrSyntax
表示语法错误,比如将空字符串转换为int
会发生ErrSyntax
错误。var ErrSyntax = errors.New("invalid syntax")
返回错误时不是直接将错误变量返回,而会通过构造一个NumError
类型的error
对象返回。
type NumError struct{
Func string
Num string
Err error
}
NumError
会记录转换过程中发生的错误信息,实现了error
接口。
func (e *NumError) Error() string{
return "strconv." + e.Func + ": " + "parsing " + Quote(e.Num) + ": " + e.Err.Error()
}
strconv
包中定义了用于构造NumError
对象的函数
函数 | 描述 |
---|---|
syntaxError | 语法错误 |
rangeError | 范围错误 |
baseError | 基础错误 |
bitSizeError | 比特位大小错误 |
函数 | 描述 |
---|---|
strconv.ParseInt | 字符串转整型 |
strconv.ParseUint | 字符串转无符号整型 |
strconv.Atoi | ParseInt的便捷版,相当于ParseInt(s, 10, 0) 。 |
strconv.ParseInt
返回字符串表示的整数值,接受正负号。func ParseInt(s string, base int, bitSize int) (i int64, err error)
参数 | 类型 | 描述 |
---|---|---|
s | string | 待转换的字符串 |
base | int | 进位制,表示字符串按照给定的进制进行解释。 |
bitSize | int | 位宽(包括符号位),表示整数的具体类型。 |
进位制
base
取值范围从2到36,比如二进制、八进制、十进制、十六进制等。base
为0是特殊情况会根据字符串前缀判断:前缀0x
表示16进制,前缀0
表示8进制,否则为10进制。base
为0的内部实现
const intSize = 32 << uint(^uint(0) >> 63)
位宽
bitSize | 类型 |
---|---|
0 | int |
8 | int8 |
16 | int16 |
32 | int32 |
64 | int64 |
返回值
bitSize
位宽能够表示的范围则会返回ErrRange
错误,同时会返回bitSize
能够表示的最大或最小值。例如:将字符串转换为十进制的int8
var s string = "1281"
i, err := strconv.ParseInt(s, 10, 8)
fmt.Printf("value = %d, type = %T\n", i, i) //value = 127, type = int64
fmt.Printf("error = %#v, type = %T\n", err, err)
err
是*strconv.NumError
类型error = &strconv.NumError{Func:"ParseInt", Num:"1281", Err:(*errors.errorString)(0xc000040010)},
type = *strconv.NumError
parseInt
返回的是int64
,为了能够容纳所有的整数。var s string = "127"
i, err := strconv.ParseInt(s, 10, 8)
fmt.Printf("value = %d, type = %T\n", i, i) //value = 127, type = int64
fmt.Println(err) //<nil>
Atoi
字面意思为array to int
,C语言中没有字符串类型,一般会将字符串定义为字符数组。int
类型,若传入的字符串无法转换则返回错误。func Atoi(s string) (int, error)
strconv.Atoi(s)
内部采用的是strconv.ParseInt(s, 10, 0)
例如:将字符串转换为十进制的int
类型
var s string = "123"
i, err := strconv.Atoi(s)
fmt.Printf("value = %d, type = %T, err = %v\n", i, i, err)
value = 123, type = int, err = <nil>
函数 | 描述 |
---|---|
strconv.ParseBool | 将字符串转换为bool 类型的值 |
strconv.ParseBool
返回字符串表示的布尔值func ParseBool(str string) (bool, error)
strconv.ParseBool
仅接受字符串的1、0、t、f、T、F、true、false、True、False、TRUE、FALSE,其他值均返回错误。例如:
var str string = "1"
b, err := strconv.ParseBool(str)
fmt.Printf("value = %v, type = %T\n", b, b)
fmt.Printf("error = %v, type = %T\n", err, err)
value = true, type = bool
error = <nil>, type = <nil>
例如:
var str string = "10"
b, err := strconv.ParseBool(str)
fmt.Printf("value = %v, type = %T\n", b, b)
fmt.Printf("error = %v, type = %T\n", err, err)
value = false, type = bool
error = strconv.ParseBool: parsing "10": invalid syntax, type = *strconv.NumError
函数 | 描述 |
---|---|
strconv.ParseFloat | 将字符串转换为单精度浮点数 |
strconv.ParseFloat
解析一个表示浮点数的字符串并返回其值func ParseFloat(s string, bitSize int) (float64, error)
参数 | 类型 | 描述 |
---|---|---|
s | string | 表示浮点数的字符串 |
bitSize | int | 期望的接收类型,32表示float32,64表示float64。 |
若s
合法则返回最为接近s
表示值的浮点数,会使用IEEE654规范进行舍入。
例如:
var str string = "3.1415926"
f64, err := strconv.ParseFloat(str, 32)
fmt.Printf("value = %v, type = %T\n", f64, f64)
fmt.Printf("error = %#v, type = %T\n", err, err)
value = 3.141592502593994, type = float64
error = <nil>, type = <nil>
字符串转其他类型
parse返回两个值,一个转换值,一个err,没有错误时,err返回的是nil,有错误,err接受错误信息。
整型转字符串
Itoa
字符串转整型
a=567
转载于:https://www.cnblogs.com/0916m/p/11484468.html