Go 中连接前导零的惯用方法

我想出了一种将前导零填充到 Go 字符串中的方法。我不确定这是否是你在 Go 中执行此操作的方式。在 Go 中是否有正确的方法来做到这一点?这是我想出的,可以在第二个 if 块中找到。我尝试谷歌看看它是否有内置的东西,但运气不佳。


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

}

对于 n = 1234 且 w = 5,输出应为 integerToStringOfFixedWidth(n, w) = "01234"。


翻阅古今
浏览 123回答 3
3回答

尚方宝剑之说

您可以使用 Sprintf/Printf (使用具有相同格式的 Sprintf 打印到字符串):package mainimport (    "fmt")func main() {    // For fixed width    fmt.Printf("%05d", 4)    // Or if you need variable widths:    fmt.Printf("%0*d", 5, 1234)}

撒科打诨

你可以这样做:func integerToStringOfFixedWidth(n, w int) string {&nbsp; &nbsp; s := fmt.Sprintf(fmt.Sprintf("%%0%dd", w), n)&nbsp; &nbsp; l := len(s)&nbsp; &nbsp; if l > w {&nbsp; &nbsp; &nbsp; &nbsp; return s[l-w:]&nbsp; &nbsp; }&nbsp; &nbsp; return s}

凤凰求蛊

使用记录良好且经过测试的包,而不是编写自己的 paddig 代码。func integerToStringOfFixedWidth(n int, w int) string {     s, _ := leftpad.PadChar(strconv.Itoa(n), w, '0')         return s }
打开App,查看更多内容
随时随地看视频慕课网APP