How can I convert an Int
to a 7-character long String
, so that 123
is turned into \"0000123\"
?
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!