How to convert an Int to a String of a given length with leading zeros to align?

前端 未结 7 1298
醉酒成梦
醉酒成梦 2020-12-12 16:40

How can I convert an Int to a 7-character long String, so that 123 is turned into \"0000123\"?

7条回答
  •  离开以前
    2020-12-12 17:27

    Short answer:

    "1234".reverse.padTo(7, '0').reverse
    

    Long answer:

    Scala StringOps (which contains a nice set of methods that Scala string objects have because of implicit conversions) has a padTo method, which appends a certain amount of characters to your string. For example:

    "aloha".padTo(10,'a')
    

    Will return "alohaaaaaa". Note the element type of a String is a Char, hence the single quotes around the 'a'.

    Your problem is a bit different since you need to prepend characters instead of appending them. That's why you need to reverse the string, append the fill-up characters (you would be prepending them now since the string is reversed), and then reverse the whole thing again to get the final result.

    Hope this helps!

提交回复
热议问题