RosettaCodeData/Task/Align-columns/8th/align-columns.8th

45 lines
995 B
Plaintext

quote | Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.|
var, raw-text
[] var, data
var width
: read-and-parse \ --
raw-text @
( "$" s:/ data @ swap a:push drop )
s:eachline ;
: find-widest \ -- n
data @ ( ( swap s:len nip n:max ) swap a:reduce ) 0 a:reduce ;
: print-data \ fmt --
width @ swap s:strfmt >r
data @
(
nip
(
nip
r@ s:strfmt .
) a:each drop
cr
) a:each drop rdrop ;
: app:main
read-and-parse
\ find widest column, and add one for the space:
find-widest n:1+ width !
\ print the data
cr "right:" . cr "%%>%ds" print-data
cr "left:" . cr "%%<%ds" print-data
cr "center:" . cr "%%|%ds" print-data
bye ;