栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Golang中将int32转换为字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Golang中将int32转换为字符串

一线的答案是

fmt.Sprint(i)

无论如何,甚至在标准库函数(例如)内部都有很多转换,

fmt.Sprint(i)
因此您有一些选择(尝试使用Go
Playground
):


1-您可以编写转换函数( 最快 ):

func String(n int32) string {    buf := [11]byte{}    pos := len(buf)    i := int64(n)    signed := i < 0    if signed {        i = -i    }    for {        pos--        buf[pos], i = '0'+byte(i%10), i/10        if i == 0 { if signed {     pos--     buf[pos] = '-' } return string(buf[pos:])        }    }}

2-您可以使用

fmt.Sprint(i)

参见内部:

// Sprint formats using the default formats for its operands and returns the resulting string.// Spaces are added between operands when neither is a string.func Sprint(a ...interface{}) string {    p := newPrinter()    p.doPrint(a)    s := string(p.buf)    p.free()    return s}

3-您可以使用

strconv.Itoa(int(i))
快速
参见内部:

// Itoa is shorthand for FormatInt(int64(i), 10).func Itoa(i int) string {    return FormatInt(int64(i), 10)}

4-您可以使用

strconv.FormatInt(int64(i), 10)
更快
请参阅内部:

// FormatInt returns the string representation of i in the given base,// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'// for digit values >= 10.func FormatInt(i int64, base int) string {    _, s := formatBits(nil, uint64(i), base, i < 0, false)    return s}

比较和基准测试(具有50000000次迭代):

s = String(i) takes:  5.5923198ss = String2(i)takes:  5.5923199ss = strconv.FormatInt(int64(i), 10) takes:  5.9133382ss = strconv.Itoa(int(i)) takes:  5.9763418ss = fmt.Sprint(i)        takes: 13.5697761s

码:

package mainimport (    "fmt"    //"strconv"    "time")func main() {    var s string    i := int32(-2147483648)    t := time.Now()    for j := 0; j < 50000000; j++ {        s = String(i) //5.5923198s        //s = String2(i) //5.5923199s        //s = strconv.FormatInt(int64(i), 10) // 5.9133382s        //s = strconv.Itoa(int(i)) //5.9763418s        //s = fmt.Sprint(i) // 13.5697761s    }    fmt.Println(time.Since(t))    fmt.Println(s)}func String(n int32) string {    buf := [11]byte{}    pos := len(buf)    i := int64(n)    signed := i < 0    if signed {        i = -i    }    for {        pos--        buf[pos], i = '0'+byte(i%10), i/10        if i == 0 { if signed {     pos--     buf[pos] = '-' } return string(buf[pos:])        }    }}func String2(n int32) string {    buf := [11]byte{}    pos := len(buf)    i, q := int64(n), int64(0)    signed := i < 0    if signed {        i = -i    }    for {        pos--        q = i / 10        buf[pos], i = '0'+byte(i-10*q), q        if i == 0 { if signed {     pos--     buf[pos] = '-' } return string(buf[pos:])        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/406465.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号