Expand/Shrink

pad

Definition: sequence res = pad(string src, integer size, string method="BOTH", integer ch=' ')
-- or --
sequence res = pad_head(string src, integer size, ch=' ')
-- or --
sequence res = pad_tail(sequence src, integer size, object ch=' ')
Description: Pad the beginning/end of a string with a specified character (default space ) so as to meet a minimum length condition.

src: the string to pad (or general sequence for pad_tail).
size: the minimum length of the result.
method: one of "HEAD", "TAIL", "BOTH", or "BLOTH" (case sensitive).
ch: the character to pad with (or any object for pad_tail, defaults to a space).

Returns src unaltered when it was already long enough, or extended to be of length size by inserting the required number of elements at the start/end(s).
pwa/p2js: Supported.
Comments: Does not remove characters. The source and result need not necessarily be the same.
If length(src) is greater than or equal to size, simply returns src unaltered.

pad_head() is the same as pad(src,size,"HEAD"[,ch]), and
pad_tail() is the same as pad(src,size,"TAIL"[,ch]), except as noted below.
Should pad("BOTH") need to add an odd number of ch, there will be one more after than before, you can also call pad("BLOTH") which adds one more before than after, when needed/uneven.

Compatibility note: there is no Euphoria pad() function, and its pad_head() function also works on dword-sequences with an object ch, which I deemed unhelpful (on both pad_head and pad), whereas pad_tail() is much more likely to be useful on a dword-sequence, so that has the less restrictive parameter types. Note however that it will (deliberately) crash on entry if src is a string but ch is not an 8-bit character, 0..255.

See also (s)printf()’s field width and '0+-=|' handling.

See head() or tail() should you wish to truncate long sequences.
Examples:
s = pad_head("ABC", 6)              -- s is "   ABC"
s = pad_head("ABC", 6, '-')         -- s is "---ABC"
s = pad("X",4,"BOTH",'.')           -- s is ".X.."
s = pad("X",4,"BLOTH",'.')          -- s is "..X."
Implementation: See builtins\pseqc.e (an autoinclude) for details of the actual implementation.