开放的编程资料库

当前位置:我爱分享网 > Go教程 > 正文

Golang中将整数转换为字符串

Gointtostringconversion教程展示了如何在Golang中将整数转换为字符串。

进入字符串转换

整数到字符串的转换是一种类型转换或类型转换,其中整数数据类型的实体被更改为字符串一。

在Go中,我们可以使用strconv.FormatIntstrconv.Itoafmt.Sprintf函数执行int到string的转换.

strconv包实现了与基本数据类型的字符串表示之间的转换。

$ go version
go version go1.18.1 linux/amd64

我们使用Go版本1.18。

使用Itoa转入字符串

Itoa是一个将整数转换为字符串的便捷函数。

func Itoa(i int) string

Itoa等价于FormatInt(int64(i),10)

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var apples int = 6

    n := strconv.Itoa(apples)
    msg := "There are " + n + " apples"
    fmt.Println(msg)

    fmt.Printf("%T\n", apples)
    fmt.Printf("%T\n", n)
}

在代码示例中,我们将苹果的数量转换为字符串以构建一条消息。稍后,我们输出applesn变量的类型。

$ go run int2str.go 
There are 6 apples
int
string

使用strconv.FormatInt将int转换为字符串

strconv.FormatInt返回给定基数中值的字符串表示形式;其中2<=base<=36.

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var file_size int64 = 1544466212

    file_size_s := strconv.FormatInt(file_size, 10)

    msg := "The file size is " + file_size_s + " bytes"
    fmt.Println(msg)
}

在代码示例中,我们将类型为int64file_size变量转换为具有strconv.FormatInt的字符串。p>

$ go run int2str2.go 
The file size is 1544466212 bytes

使用fmt.Sprintf转换为字符串

将整数转换为字符串的另一种方法是使用fmt.Sprintf函数。该函数根据格式说明符格式化并返回结果字符串。

package main

import (
    "fmt"
)

func main() {

    var apples int = 6

    msg := fmt.Sprintf("There are %d apples", apples)
    fmt.Println(msg)
}

fmt.Sprintf格式化一个新字符串;它将%d说明符替换为整数值。

在本教程中,我们展示了如何在Go中执行int到字符串的转换。

列出所有Go教程。

未经允许不得转载:我爱分享网 » Golang中将整数转换为字符串

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏