zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Go-标准库-strconv(二)

2023-06-13 09:18:47 时间

FormatFloat:将浮点型转换为字符串

FormatFloat函数将float64类型的数据转换为字符串,并允许指定转换的格式和精度。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	f := 3.1415926535
	str := strconv.FormatFloat(f, 'E', -1, 64)
	fmt.Printf("str is %s\n", str)
}

输出结果:

str is 3.1415926535E+00

Quote:为字符串添加引号

Quote函数将字符串添加上双引号,并且对特殊字符进行转义。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "Hello, World!"
	q := strconv.Quote(str)
	fmt.Printf("q is %s\n", q)
}

输出结果:

csharpCopy codeq is "Hello, World!"

Append系列函数:将不同类型的数据转换为字符串并追加到字节数组中

Append系列函数将不同类型的数据转换为字符串并追加到字节数组中,函数名以Append开头,后面跟上转换的类型名称。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "Hello, World!"
	b := []byte(str)
	b = strconv.AppendInt(b, 123, 10)
	b = strconv.AppendBool(b, true)
	b = strconv.AppendQuote(b, "Golang")
	fmt.Printf("b is %s\n", b)
}

输出结果:

b is Hello, World!123true"Golang"

Can系列函数:判断字符串是否可以转换为指定的类型

Can系列函数用于判断字符串是否可以转换为指定的类型,函数名以Can开头,后面跟上转换的类型名称。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "123"
	if strconv.CanInt64(str) {
		i64, _ := strconv.ParseInt(str, 10, 64)
		fmt.Printf("i64 is %d\n", i64)
	} else {
		fmt.Println("conversion failed")
	}
}

输出结果:

i64 is 123