I was recently implementing the following algorithm (written for clarity; there are many ways to write it more compactly):
tmp = str.length % blocksize
if (tmp == 0)
tmp = blocksize
tmp = blocksize - tmp
str.append(padchar * tmp)
It ensues the string str
is a multiple of blocksize
, padding with padchar
as necessary. I've found myself implementing this often enough, that today I implemented it yet again, and realized that it must be common enough to have a proper name or be in some common libraries, yet I've never seen or heard of it. This example is left-justified, but I could imagine a similar right-variant. My attempts at googling "chunk justification" or "block justification" turned up nothing. It isn't standard left or right justification, as all api's for those that I've seen are fixed length, whereas this is semi-variable length.
So, my two questions:
- Does this have a more formal name?
- Is this algorithm implemented in any language standard library or common utilities?
(note that although I've used strings in this question, the algorithm works just as well for, and I'm just as interested in answers for generic lists/arrays)
Example output:
> thisalgo(str="hey!", blocksize=5, padchar='0')
"hey!0"
> thisalgo(str="hello", blocksize=5, padchar='0')
"hello"
> thisalgo(str="hello!", blocksize=5, padchar='0')
"hello!0000"