2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nimでゼロ埋め

Last updated at Posted at 2018-05-30

Nimでゼロ埋めしたいと思っただけ。

import strformat, strutils
let
  n = 6
  s = "5"

# int型
doAssert fmt"{n:04}" == "0006"

# string型の場合parseIntする
doAssert fmt"{s.parseInt:03}" == "005"

string型はformat関数でも出来そうでしたが,ゼロ埋めだけならintに変換してしまう方が楽だと思いました。(ドキュメントの英語がよくわからなかった)

詳しくはstrformatの公式ドキュメント

18/06/01追記
@2vgさんにalignを使う方法を教えていただきました。ありがとうございます。

import strutils

var a: string = ""
doAssert a.align(5, '0') == "00000"

a = "123"
doAssert a.align(5, '0') == "00123"
doAssert a.align(6, '#') == "###123"

もとの値がint型で0またはスペースで埋めたいだけならfmtの上の方法,
もとの値がstring型で0やスペース以外で埋めたい場合はalignを使うのが良さそうですね。

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?