doukan5332 2019-09-06 19:57
浏览 62

惯用方式在Go中连接前导零

I came up with a way to pad leading zeros into a Go string. I'm not sure if this is the way you do this in Go. Is there a proper way to do this in Go? This is what I came up with and can be found inside the second if block. I tried Google to see if it had something built in without luck.

func integerToStringOfFixedWidth(n int, w int) string {
  s := strconv.Itoa(n)
  l := len(s)

  if l < w {
    for i := l; i < w; i++ {
      s = "0" + s
    }
    return s
  }
  if l > w {
    return s[l-w:]
  }
  return s
}

For n = 1234 and w = 5, the output should be integerToStringOfFixedWidth(n, w) = "01234".

  • 写回答

3条回答 默认 最新

  • douliexu5623 2019-09-06 20:03
    关注

    You can use Sprintf/Printf for that (Use Sprintf with the same format to print to a string):

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        // For fixed width
        fmt.Printf("%05d", 4)
    
        // Or if you need variable widths:
        fmt.Printf("%0*d", 5, 1234)
    }
    

    https://golang.org/pkg/fmt/

    See other flags in the docs - pad with leading zeros rather than spaces

    https://play.golang.org/p/0EM4aE2Hk6H

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集