Jump to content

Align columns: Difference between revisions

→‎{{header|D}}: add implementation
(→‎{{header|D}}: add implementation)
Line 550:
(princ "~}~%~}" s))
fields))</lang>
 
=={{header|D}}==
<lang d>
import std.stdio;
import std.string;
char[]text = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n"
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n"
"column$are$separated$by$at$least$one$space.\n"
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"justified,$right$justified,$or$center$justified$within$its$column.";
 
int main() {
char[][]lines = text.split("\n");
char[][][]words;
int[]maxlens;
foreach(line;lines) {
words ~= line.split("$");
// make sure we have enough slots in maxlens
if (words[$-1].length > maxlens.length) {
maxlens.length = words[$-1].length;
}
foreach(i,word;words[$-1]) {
if (word.length > maxlens[i]) maxlens[i] = word.length;
}
}
// now that we've done a whole pass and grabbed all the max lengths, start over and pad everything to the right length
foreach(line;words) foreach(i,ref word;line) {
word ~= repeat(" ",maxlens[i]-word.length);
}
// now join all the words back into lines and print them
foreach(line;words) {
writefln("%s",line.join(" "));
}
return 0;
}
</lang>
 
=={{header|E}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.