Align columns: Difference between revisions

→‎{{header|D}}: fix this example, my bad on the original
m (→‎{{header|J}}: simplify parsing)
(→‎{{header|D}}: fix this example, my bad on the original)
Line 552:
 
=={{header|D}}==
{{incorrect|D|(Actually, it is '''incomplete'''). This seems as if it might generate a correct left justified output , but right and center justification, (and maybe sample output), are missing.}}
 
<lang d>
Line 563 ⟶ 562:
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"justified,$right$justified,$or$center$justified$within$its$column.";
 
enum PadType {
LEFT,
RIGHT,
CENTER,
LEFT_CENTER,
RIGHT_CENTER
}
 
int main() {
Line 578 ⟶ 585:
}
}
// output everything with all 3 padding types
// 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 ~= repeatforeach("i,ref ",maxlens[i]-word.length;line); {
writef("%s ",padData(word,maxlens[i],PadType.LEFT));
}
writefln("");
}
// now join all the words back into lines and print them
foreach(line;words) {
writeflnforeach("%s"i,ref word;line.join(") "));{
writef("%s ",padData(word,maxlens[i],PadType.RIGHT));
}
writefln("");
}
foreach(line;words) {
foreach(i,ref word;line) {
writef("%s ",padData(word,maxlens[i],PadType.CENTER));
}
writefln("");
}
return 0;
}
 
char[]padData(char[]data,int length,PadType type) {
int diff = length - data.length;
switch(type) {
case PadType.CENTER:
case PadType.LEFT_CENTER:
// the +1 in the second part takes care of odd differences, since this is integer math
// odd differences will result in a slight left-of-center alignment
return repeat(" ",diff/2)~data~repeat(" ",(diff+1)/2);
case PadType.RIGHT_CENTER:
// the +1 in the second part takes care of odd differences, since this is integer math
// odd differences will result in a slight right-of-center alignment
return repeat(" ",(diff+1)/2)~data~repeat(" ",diff/2);
case PadType.RIGHT:
return repeat(" ",diff)~data;
case PadType.LEFT:
return data~repeat(" ",diff);
}
}
</lang>
Anonymous user