Align columns: Difference between revisions
Content added Content deleted
m (→{{header|J}}: simplify parsing) |
(→{{header|D}}: fix this example, my bad on the original) |
||
Line 552: | Line 552: | ||
=={{header|D}}== |
=={{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> |
<lang d> |
||
Line 563: | Line 562: | ||
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" |
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" |
||
"justified,$right$justified,$or$center$justified$within$its$column."; |
"justified,$right$justified,$or$center$justified$within$its$column."; |
||
enum PadType { |
|||
LEFT, |
|||
RIGHT, |
|||
CENTER, |
|||
LEFT_CENTER, |
|||
RIGHT_CENTER |
|||
} |
|||
int main() { |
int main() { |
||
Line 578: | Line 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(line;words) { |
||
foreach(i,ref word;line) { |
|||
writef("%s ",padData(word,maxlens[i],PadType.LEFT)); |
|||
} |
|||
writefln(""); |
|||
} |
} |
||
// now join all the words back into lines and print them |
|||
foreach(line;words) { |
foreach(line;words) { |
||
foreach(i,ref word;line) { |
|||
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; |
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> |
</lang> |