golang_字符串转换: Strconv包中append,Format,Parse,Itoa,Atoi的用法介绍

本文介绍了Golang中的strconv包,包括strconv.append系列(将各种类型转化为字符串并追加到字节数组),strconv.Format系列(其他类型转字符串),strconv.Parse系列(字符串转其他类型),strconv.Itoa(整型转字符串)以及strconv.Atoi(字符串转整型)。通过这些函数,开发者可以方便地在不同数据类型间进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串转换:

Strconv包
1.Strconv.append系列: 转化为字符串后追加到字节数组
	s1 := make([]byte,0,1024)
	s1 = strconv.AppendBool(s1,true)
	s1 = strconv.AppendInt(s1,123,10) //第三个参数base int,进制数
	s1 = strconv.AppendQuote(s1,"go")
	fmt.Println("s1 =",s1) //s1 = [116 114 117 101 49 50 51 34 103 111 34]
	fmt.Println("s1 =",string(s1)) //s1 = true123"go"

func AppendBool(dst []byte, b bool) []byte
func AppendInt(dst []byte, i int64, base int) []byte
func AppendUint(dst []byte, i uint64, base int) []byte
func AppendFloat(dst []byte, f float64, fmt byte, prec int, bitSize int) []byte
func AppendQuote(dst []byte, s string) []byte
func AppendQuoteToASCII(dst []byte, s string) []byte
func AppendQuoteRune(dst []byte, r rune) []byte
func AppendQuoteRuneToASCII(dst []byte, r rune) []byte

2.Strconv.Format系列: 其他类型转字符串
	s2 := strconv.FormatBool(false)
	fmt.Println("s2 =",s2) //s2 = false

	//"f"-打印格式,-1小数点位数(排除指数位数),64-y以float64处理
	s3 := strconv.FormatFloat(3.14,'f',-1,64)
	fmt.Println("s3 =",s3) //s3 = 3.14

func FormatBool(b bool) string
func FormatInt(i int64, base int) string
func FormatUint(i uint64, base int) string
func FormatFloat(f float64, fmt byte, prec, bitSize int) string

3.Strconv.Parse系列: 字符串转其他类型
	flag,err := strconv.ParseBool("true")
	if err == nil{  //如果err为空,即没有错误,打印正确的输出
		fmt.Println("flag =",flag) //flag = true
	}else{
		fmt.Println("err= ",err)
	}

func ParseBool(str string) (value bool, err error)
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (n uint64, err error)
func ParseFloat(s string, bitSize int) (f float64, err error)

4.strconv.Itoa : 整型转字符串
	str := strconv.Itoa(123)
	fmt.Println("str =",str) //str = 123
5.strconv.Atoi : 字符串转整型
	num, err := strconv.Atoi("1a23") 
	if err == nil{
		fmt.Println("num =",num)
	}else{
		fmt.Println("err= ",err) //输入字符中包含"a",无法打印
		//err=  strconv.Atoi: parsing "1a23": invalid syntax
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值