Anonymous user
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}}==
<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
foreach(line;words
writef("%s ",padData(word,maxlens[i],PadType.LEFT));
}
writefln("");
}
foreach(line;words) {
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>
|