59_字符串的转换

代码如下

package main

import (
"fmt"
"strconv"
)

func main() {

//1.append系列函数:转换为字符串后,追加到字节数组
//func AppendBool(dst []byte, b bool) []byte
s1 := []byte{'a', 'b', 'c'}
s2 := strconv.AppendBool(s1, true)
fmt.Println(s2) //[97 98 99 116 114 117 101]
fmt.Println("s2=", string(s2)) //s2= abctrue

//将34以十进制的方式追加到s1中
s3 := strconv.AppendInt(s1, 34, 10)
fmt.Println("s3=", string(s3)) //s3= abc34

//将字符序列添加到字符串中
s4 := strconv.AppendQuote(s1, "qwew")
fmt.Println("s4=", string(s4)) //s4= abc"qwew"

//2.fotmat:将其他类型转换成字符串类型
var str string
str = strconv.FormatBool(false) //将布尔类型,转换成字符串类型
fmt.Println(str) //false

//func FormatFloat(f float64, fmt byte, prec, bitSize int) string
//fmt表示格式:'f'(-ddd.dddd);bitSize表示f的来源类型(32:float32、64:float64)
//prec控制精度;
str = strconv.FormatFloat(3.14, 'f', -1, 64)
fmt.Println(str) //3.14

//整型转换为字符串常用方法
str = strconv.Itoa(666)
fmt.Printf("str=%T,str=%v\n", str, str) //str=string,str=666

//3.parse字符串转换成其他类型
ss := "steven is a people"
//它接受1、0、t、f、T、F、true、false、True、False、TRUE、FALSE;否则返回错误。
ss1, err := strconv.ParseBool(ss)
fmt.Println(ss1, err) //false
ss1, err = strconv.ParseBool("1")
fmt.Println(ss1, err) //true err:<nil>

//常用把字符串转换成整型
ss3, _ := strconv.Atoi("6677")
fmt.Printf("ss3=%T,ss3=%v\n", ss3, ss3) //ss3=int,ss3=6677
}

猜你喜欢

转载自www.cnblogs.com/zhaopp/p/11625911.html