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

版权声明:版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_43851310/article/details/87731063

字符串转换:

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
	}

猜你喜欢

转载自blog.csdn.net/weixin_43851310/article/details/87731063