Go语言中strconv
包实现了基本数据类型和其字符串表示的相互转换。
strconv包实现了基本数据类型与其字符串表示的转换,主要有以下常用函数: Atoi()
、Itoa()
、parse系列、format系列、append系列。
package main
import (
"fmt"
"strconv"
)
func main() {
//字符串转换成int
str := "100"
fmt.Printf("%#v\n", str)
retInt, _ := strconv.Atoi(str)
fmt.Printf("%#v %T\n", retInt, retInt)
//int转成字符串
i := 97
retStr := strconv.Itoa(i)
fmt.Printf("%#v %T\n", retStr, retStr)
//字符串解析出浮点数值
floatStr := "1.234"
floatValue, _ := strconv.ParseFloat(floatStr, 64)
fmt.Printf("%v %T\n", floatValue, floatValue)
//从字符串解析出布尔值
boolStr := "true"
boolValue, _ := strconv.ParseBool(boolStr)
fmt.Printf("%v %T\n", boolValue, boolValue)
//从字符串中解析出整行
str1 := "1000"
ret1, _ := strconv.ParseInt(str1, 10, 32)
fmt.Printf("%v %T\n", ret1, ret1)
//Format系列函数
//布尔值转换成string类型
bool := true
strValue := strconv.FormatBool(bool)
fmt.Printf("%#v %T\n", strValue, strValue)
//int转换成string类型
i1 := 97
intValue := strconv.FormatInt(int64(i1), 10)
fmt.Printf("%#v %T\n", intValue, intValue)
//浮点型转换成string类型
f := 1.234
floatValue1 := strconv.FormatFloat(f, 'e', -1, 64)
fmt.Printf("%#v %T\n", floatValue1, floatValue1)
}