Align columns: Difference between revisions

Added XPL0 example.
(Added solution for Action!)
(Added XPL0 example.)
 
(31 intermediate revisions by 19 users not shown)
Line 30:
=={{header|11l}}==
{{trans|D}}
<langsyntaxhighlight lang="11l">V txt = ‘Given$a$txt$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$
Line 53:
print(justify(word, max_widths[L.index]), end' ‘ ’)
print()
print(‘- ’ * 52)</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Align columns 12/04/2019
ALICOL CSECT
USING ALICOL,R13 base register
Line 235:
PG DS CL120
REGEQU
END ALICOL </langsyntaxhighlight>
{{out}}
<pre>
Line 262:
 
=={{header|8th}}==
<syntaxhighlight lang="forth">
<lang Forth>
quote | Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 308:
bye ;
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 335:
justified, right justified, or center justified within its column.
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program alignColumn64.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
.equ BUFFERSIZE, 16 * 10
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessLeft: .asciz "LEFT :\n"
szMessRight: .asciz "\nRIGHT :\n"
szMessCenter: .asciz "\nCENTER :\n"
szCarriageReturn: .asciz "\n"
 
szLine1: .asciz "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
szLine2: .asciz "are$delineated$by$a$single$'dollar'$character,$write$a$program"
szLine3: .asciz "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
szLine4: .asciz "column$are$separated$by$at$least$one$space."
szLine5: .asciz "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
szLine6: .asciz "justified,$right$justified,$or$center$justified$within$its$column."
 
.align 8
qtbPtLine: .quad szLine1,szLine2,szLine3,szLine4,szLine5,szLine6
.equ NBLINES, (. - qtbPtLine) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrqtbPtLine
bl computeMaxiLengthWords
mov x19,x0 // column counter
ldr x0,qAdrszMessLeft
bl affichageMess
ldr x0,qAdrqtbPtLine
mov x1,x19 // column size
bl alignLeft
ldr x0,qAdrszMessRight
bl affichageMess
ldr x0,qAdrqtbPtLine
mov x1,x19 // column size
bl alignRight
ldr x0,qAdrszMessCenter
bl affichageMess
ldr x0,qAdrqtbPtLine
mov x1,x19 // column size
bl alignCenter
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessLeft: .quad szMessLeft
qAdrszMessRight: .quad szMessRight
qAdrszMessCenter: .quad szMessCenter
qAdrqtbPtLine: .quad qtbPtLine
/******************************************************************/
/* compute maxi words */
/******************************************************************/
/* x0 contains adresse pointer array */
computeMaxiLengthWords:
stp fp,lr,[sp,-16]! // save registres
mov x2,#0 // indice pointer array
mov x3,#0 // maxi length words
1:
ldr x1,[x0,x2,lsl #3] // load pointer
mov x4,#0 // length words counter
mov x5,#0 // indice line character
2:
ldrb w6,[x1,x5] // load a line character
cmp x6,#0 // line end ?
beq 4f
cmp x6,#'$' // separator ?
bne 3f
cmp x4,x3
csel x3,x4,x3,gt // if greather replace maxi
mov x4,#-1 // raz length counter
3:
add x4,x4,#1
add x5,x5,#1 // increment character indice
b 2b // and loop
4: // end line
cmp x4,x3 // compare word counter and maxi
csel x3,x4,x3,gt // if greather replace maxi
add x2,x2,#1 // increment indice line pointer
cmp x2,#NBLINES // maxi ?
blt 1b // no -> loop
 
mov x0,x3 // return maxi length counter
100:
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
 
/******************************************************************/
/* align left */
/******************************************************************/
/* x0 contains the address of pointer array*/
/* x1 contains column size */
alignLeft:
stp fp,lr,[sp,-16]! // save registres
sub sp,sp,#BUFFERSIZE // reserve place for output buffer
mov fp,sp
mov x5,x0 // array address
mov x2,#0 // indice array
1:
ldr x3,[x5,x2,lsl #3] // load line pointer
mov x4,#0 // line character indice
mov x7,#0 // output buffer character indice
mov x6,#0 // word lenght
2:
ldrb w0,[x3,x4] // load a character line
strb w0,[fp,x7] // store in buffer
cmp w0,#0 // line end ?
beq 6f
cmp w0,#'$' // separator ?
bne 5f
mov x0,#' '
strb w0,[fp,x7] // replace $ by space
3:
cmp x6,x1 // length word >= length column
bge 4f
add x7,x7,#1
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x6,x6,#1
b 3b // and loop
4:
mov x6,#-1 // raz word length
5:
add x4,x4,#1 // increment line indice
add x7,x7,#1 // increment buffer indice
add x6,x6,#1 // increment word length
b 2b
6:
mov x0,#'\n'
strb w0,[fp,x7] // return line
add x7,x7,#1
mov x0,#0
strb w0,[fp,x7] // final zéro
mov x0,fp
bl affichageMess // display output buffer
add x2,x2,#1
cmp x2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* align right */
/******************************************************************/
/* x0 contains the address of pointer array*/
/* x1 contains column size */
alignRight:
stp fp,lr,[sp,-16]! // save registres
sub sp,sp,#BUFFERSIZE // reserve place for output buffer
mov fp,sp
mov x5,x0 // array address
mov x2,#0 // indice array
1:
ldr x3,[x5,x2,lsl #3] // load line pointer
mov x4,#0 // line character indice
mov x7,#0 // output buffer character indice
mov x6,#0 // word lenght
mov x8,x3 // word begin address
2: // compute word length
ldrb w0,[x3,x4] // load a character line
cmp w0,#0 // line end ?
beq 3f
cmp w0,#'$' // separator ?
beq 3f
add x4,x4,#1 // increment line indice
add x6,x6,#1 // increment word length
b 2b
 
3:
cmp x6,#0
beq 4f
sub x6,x1,x6 // compute left spaces to add
4: // loop add spaces to buffer
cmp x6,#0
blt 5f
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x7,x7,#1
sub x6,x6,#1
b 4b // and loop
5:
mov x9,#0
6: // copy loop word to buffer
ldrb w0,[x8,x9]
cmp x0,#'$'
beq 7f
cmp x0,#0 // line end
beq 8f
strb w0,[fp,x7]
add x7,x7,#1
add x9,x9,#1
b 6b
7:
add x8,x8,x9
add x8,x8,#1 // new word begin
mov x6,#0 // raz word length
add x4,x4,#1 // increment line indice
b 2b
8:
mov x0,#'\n'
strb w0,[fp,x7] // return line
add x7,x7,#1
mov x0,#0
strb w0,[fp,x7] // final zéro
mov x0,fp
bl affichageMess // display output buffer
add x2,x2,#1
cmp x2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* align center */
/******************************************************************/
/* x0 contains the address of pointer array*/
/* x1 contains column size */
alignCenter:
stp fp,lr,[sp,-16]! // save registres
sub sp,sp,#BUFFERSIZE // reserve place for output buffer
mov fp,sp
mov x5,x0 // array address
mov x2,#0 // indice array
1:
ldr x3,[x5,x2,lsl #3] // load line pointer
mov x4,#0 // line character indice
mov x7,#0 // output buffer character indice
mov x6,#0 // word length
mov x8,x3 // word begin address
2: // compute word length
ldrb w0,[x3,x4] // load a character line
cmp w0,#0 // line end ?
beq 3f
cmp w0,#'$' // separator ?
beq 3f
add x4,x4,#1 // increment line indice
add x6,x6,#1 // increment word length
b 2b
3:
cmp x6,#0
beq 5f
sub x6,x1,x6 // total spaces number to add
mov x12,x6
lsr x6,x6,#1 // divise by 2 = left spaces number
4:
cmp x6,#0
blt 5f
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x7,x7,#1 // increment output indice
sub x6,x6,#1 // decrement number space
b 4b // and loop
5:
mov x9,#0
6: // copy loop word to buffer
ldrb w0,[x8,x9]
cmp x0,#'$' // séparator ?
beq 7f
cmp x0,#0 // line end ?
beq 10f
strb w0,[fp,x7]
add x7,x7,#1
add x9,x9,#1
b 6b
7:
lsr x6,x12,#1 // divise total spaces by 2
sub x6,x12,x6 // and compute number spaces to right side
8: // loop to add right spaces
cmp x6,#0
ble 9f
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x7,x7,#1
sub x6,x6,#1
b 8b // and loop
 
9:
add x8,x8,x9
add x8,x8,#1 // new address word begin
mov x6,#0 // raz word length
add x4,x4,#1 // increment line indice
b 2b // and loop new word
10:
mov x0,#'\n'
strb w0,[fp,x7] // return line
add x7,x7,#1
mov x0,#0
strb w0,[fp,x7] // final zéro
mov x0,fp
bl affichageMess // display output buffer
add x2,x2,#1 // increment line indice
cmp x2,#NBLINES // maxi ?
blt 1b // loop
100:
add sp,sp,#BUFFERSIZE
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
LEFT :
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.
 
RIGHT :
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.
 
CENTER :
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.
</pre>
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">report z_align no standard page header.
start-of-selection.
 
Line 413 ⟶ 769:
sy-linno = sy-linno - 1.
endloop.
endform.</langsyntaxhighlight>
 
<pre style="height:15ex;overflow:scroll">Given a text file of many lines, where fields within a line
Line 438 ⟶ 794:
=={{header|Action!}}==
Atari 8-bit computer is able to show only 40 characters per line. The user has to press left/right arrow keys to scroll the content of whole text.
<langsyntaxhighlight Actionlang="action!">DEFINE LINES_COUNT="10"
DEFINE COLUMNS_COUNT="20"
DEFINE WORDS_COUNT="100"
DEFINE BUFFER_SIZE="2000"
DEFINE LINE_WIDTH="40"
DEFINE PTR="CARD"
 
CARDPTR ARRAY lines(LINES_COUNT)
BYTE ARRAY wordStart(WORDS_COUNT)
BYTE ARRAY wordLen(WORDS_COUNT)
Line 526 ⟶ 883:
RETURN (c)
 
PROC GenerateLine(BYTE index BYTE align BYTE POINTER p)
BYTE POINTER ptr)
BYTE wordIndex,last,left,right,start,len,colW
INT i,j
Line 539 ⟶ 895:
colW=colWidths(i)
 
ptrp^=124 ptrp==+1
IF wordIndex<=last THEN
start=wordStart(wordIndex)
Line 555 ⟶ 911:
FI
 
ptrp==+left
for j=start TO start+len-1
DO
ptrp^=AtasciiToInternal(line(j))
ptrp==+1
OD
ptrp==+right
ELSE
ptrp==+colW
FI
 
wordIndex==+1
OD
ptrp^=124
RETURN
 
PROC FillBuffer(BYTE lineWidth)
BYTE i,align
BYTE POINTER ptrp
 
ptrp=buffer
Zero(ptrp,BUFFER_SIZE)
FOR align=0 TO 2
DO
FOR i=0 TO lineCount-1
DO
GenerateLine(i,align,ptrp)
ptrp==+lineWidth
OD
OD
Line 645 ⟶ 1,001:
FI
OD
 
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Align_columns.png Screenshot from Atari 8-bit computer]
Line 675 ⟶ 1,032:
=={{header|Ada}}==
{{libheader|Simple components for Ada}}
<langsyntaxhighlight lang="ada">with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Text_IO; use Ada.Text_IO;
with Strings_Edit; use Strings_Edit;
Line 739 ⟶ 1,096:
end loop;
Close (File);
end Column_Aligner;</langsyntaxhighlight>
Formatted file sample:
<pre style="height:15ex;overflow:scroll">
Line 763 ⟶ 1,120:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">data b;
file f;
text n, t;
Line 807 ⟶ 1,164:
}
o_newline();
}</langsyntaxhighlight>
{{Out}}
<pre>left justified
Line 834 ⟶ 1,191:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">STRING nl = REPR 10;
STRING text in list := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"+nl+
"are$delineated$by$a$single$'dollar'$character,$write$a$program"+nl+
Line 899 ⟶ 1,256:
aligner(page, align OF aligners[index])
OD
END</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#define IGet(__N__,__X__) [__N__]SGet(__X__)
 
#include <hbasic.h>
#define MAX_LINE 1000
 
Begin
Option Stack 15
Declare as Numeric ( fd, i, index, max token )
as Numeric ( num tokens, size Column, tCells )
as Alpha ( line )
as Numeric ( display Left, display Right, display Center )
GetParam(script, file to edit, separator)
 
// get statistics of file: #lines, #total chars, line more long, and num tokens from first line.
Token Sep( separator )
Stat( file to edit, dats )
// declare arrays to work:
Dim ( IGet(1,dats), Add(IGet(4,dats),10) ) for Fill Array("",cells)
Clear(dats)
MStore ( cells, display Left, display Right, display Center )
// read each line as array, get # of elements, and put into array cells:
Open(OPEN_READ, file to edit ) (fd)
When( File Error ){ Stop }
 
index=1
While Not Eof(fd)
ReadRow(MAX_LINE)(fd) and Copy to (line); get Length, and Move to (num tokens)
Set Interval [index, 1:num tokens]; Take( line ) and SPut(cells)
When ( var( max token) Is Lt (num tokens) ) { max token = num tokens }
++index
Wend
Close(fd)
 
// formatting...
For Up( i:=1, max token, 1 )
Set Interval [1:end,i], and Let ( size Column := MaxValue( Len(Get(cells)) ) Plus(1) )
Let ( tCells := Get(cells) )
LPad$( " ", size Column, tCells ), and Put(display Left)
RPad$( " ", size Column, tCells ), and Put(display Right)
CPad$( " ", size Column, tCells ), and Put(display Center)
Next
 
// display:
Token Sep ("")
Print("Left Pad:\n", display Left, Newl, "Right Pad:\n", display Right, Newl, "Center Pad:\n", display Center,Newl)
End
</syntaxhighlight>
{{out}}
Sample String was saved into "sample.txt" file.
<pre>
$ hopper src/acolumns.bas sample.txt "$"
Left Pad:
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.
 
Right Pad:
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.
 
Center Pad:
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.
$
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">align←{
left ← {⍺↑⍵}
right ← {(-⍺)↑⍵}
center ← {⍺↑(-⌊(≢⍵)+(⍺-≢⍵)÷2)↑⍵}
text ← ⊃⎕NGET⍵
words ← ((≠∘'$')⊆⊣)¨(~text∊⎕TC)⊆text
sizes ← 1+⌈⌿↑≢¨¨words
method ← ⍎⍺
↑,/↑(⊂sizes)method¨¨↓↑words
}</syntaxhighlight>
{{out}}
<pre> 'left' align 'test.txt'
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.
'center' align 'test.txt'
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.
'right' align 'test.txt'
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.</pre>
=={{header|AppleScript}}==
 
Line 906 ⟶ 1,380:
 
{{trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">-- COLUMN ALIGNMENTS ---------------------------------------------------------
 
property pstrLines : ¬
Line 1,157 ⟶ 1,631:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre> Given a text file of many lines, where fields within a line
Line 1,180 ⟶ 1,654:
justified, right justified, or center justified within its column. </pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program alignColumn.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ BUFFERSIZE, 20 * 10
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessLeft: .asciz "LEFT :\n"
szMessRight: .asciz "\nRIGHT :\n"
szMessCenter: .asciz "\nCENTER :\n"
szCarriageReturn: .asciz "\n"
 
szLine1: .asciz "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
szLine2: .asciz "are$delineated$by$a$single$'dollar'$character,$write$a$program"
szLine3: .asciz "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
szLine4: .asciz "column$are$separated$by$at$least$one$space."
szLine5: .asciz "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
szLine6: .asciz "justified,$right$justified,$or$center$justified$within$its$column."
 
itbPtLine: .int szLine1,szLine2,szLine3,szLine4,szLine5,szLine6
.equ NBLINES, (. - itbPtLine) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdritbPtLine
bl computeMaxiLengthWords
mov r10,r0 @ column counter
ldr r0,iAdrszMessLeft
bl affichageMess
ldr r0,iAdritbPtLine
mov r1,r10 @ column size
bl alignLeft
ldr r0,iAdrszMessRight
bl affichageMess
ldr r0,iAdritbPtLine
mov r1,r10 @ column size
bl alignRight
ldr r0,iAdrszMessCenter
bl affichageMess
ldr r0,iAdritbPtLine
mov r1,r10 @ column size
bl alignCenter
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessLeft: .int szMessLeft
iAdrszMessRight: .int szMessRight
iAdrszMessCenter: .int szMessCenter
iAdritbPtLine: .int itbPtLine
/******************************************************************/
/* compute maxi words */
/******************************************************************/
/* r0 contains adresse pointer array */
computeMaxiLengthWords:
push {r1-r6,lr} @ save registers
mov r2,#0 @ indice pointer array
mov r3,#0 @ maxi length words
1:
ldr r1,[r0,r2,lsl #2] @ load pointer
mov r4,#0 @ length words counter
mov r5,#0 @ indice line character
2:
ldrb r6,[r1,r5] @ load a line character
cmp r6,#0 @ line end ?
beq 4f
cmp r6,#'$' @ separator ?
bne 3f
cmp r4,r3
movgt r3,r4 @ ig greather replace maxi
mov r4,#-1 @ raz length counter
3:
add r4,r4,#1
add r5,r5,#1 @ increment character indice
b 2b @ and loop
4: @ end line
cmp r4,r3 @ compare word counter and maxi
movgt r3,r4 @ if greather replace maxi
add r2,r2,#1 @ increment indice line pointer
cmp r2,#NBLINES @ maxi ?
blt 1b @ no -> loop
 
mov r0,r3 @ return maxi length counter
100:
pop {r1-r6,pc}
 
/******************************************************************/
/* align left */
/******************************************************************/
/* r0 contains the address of pointer array*/
/* r1 contains column size */
alignLeft:
push {r4-r7,fp,lr} @ save registers
sub sp,sp,#BUFFERSIZE @ reserve place for output buffer
mov fp,sp
mov r5,r0 @ array address
mov r2,#0 @ indice array
1:
ldr r3,[r5,r2,lsl #2] @ load line pointer
mov r4,#0 @ line character indice
mov r7,#0 @ output buffer character indice
mov r6,#0 @ word lenght
2:
ldrb r0,[r3,r4] @ load a character line
strb r0,[fp,r7] @ store in buffer
cmp r0,#0 @ line end ?
beq 6f
cmp r0,#'$' @ separator ?
bne 5f
mov r0,#' '
strb r0,[fp,r7] @ replace $ by space
3:
cmp r6,r1 @ length word >= length column
bge 4f
add r7,r7,#1
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r6,r6,#1
b 3b @ and loop
4:
mov r6,#-1 @ raz word length
5:
add r4,r4,#1 @ increment line indice
add r7,r7,#1 @ increment buffer indice
add r6,r6,#1 @ increment word length
b 2b
6:
mov r0,#'\n'
strb r0,[fp,r7] @ return line
add r7,r7,#1
mov r0,#0
strb r0,[fp,r7] @ final zéro
mov r0,fp
bl affichageMess @ display output buffer
add r2,r2,#1
cmp r2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
pop {r4-r7,fp,pc}
/******************************************************************/
/* align right */
/******************************************************************/
/* r0 contains the address of pointer array*/
/* r1 contains column size */
alignRight:
push {r4-r9,fp,lr} @ save registers
sub sp,sp,#BUFFERSIZE @ reserve place for output buffer
mov fp,sp
mov r5,r0 @ array address
mov r2,#0 @ indice array
1:
ldr r3,[r5,r2,lsl #2] @ load line pointer
mov r4,#0 @ line character indice
mov r7,#0 @ output buffer character indice
mov r6,#0 @ word lenght
mov r8,r3 @ word begin address
2: @ compute word length
ldrb r0,[r3,r4] @ load a character line
cmp r0,#0 @ line end ?
beq 3f
cmp r0,#'$' @ separator ?
beq 3f
add r4,r4,#1 @ increment line indice
add r6,r6,#1 @ increment word length
b 2b
 
3:
cmp r6,#0
beq 4f
sub r6,r1,r6 @ compute left spaces to add
4: @ loop add spaces to buffer
cmp r6,#0
blt 5f
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r7,r7,#1
sub r6,r6,#1
b 4b @ and loop
5:
mov r9,#0
6: @ copy loop word to buffer
ldrb r0,[r8,r9]
cmp r0,#'$'
beq 7f
cmp r0,#0 @ line end
beq 8f
strb r0,[fp,r7]
add r7,r7,#1
add r9,r9,#1
b 6b
7:
add r8,r8,r9
add r8,r8,#1 @ new word begin
mov r6,#0 @ raz word length
add r4,r4,#1 @ increment line indice
b 2b
8:
mov r0,#'\n'
strb r0,[fp,r7] @ return line
add r7,r7,#1
mov r0,#0
strb r0,[fp,r7] @ final zéro
mov r0,fp
bl affichageMess @ display output buffer
add r2,r2,#1
cmp r2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
pop {r4-r9,fp,pc}
/******************************************************************/
/* align center */
/******************************************************************/
/* r0 contains the address of pointer array*/
/* r1 contains column size */
alignCenter:
push {r4-r12,lr} @ save registers
sub sp,sp,#BUFFERSIZE @ reserve place for output buffer
mov fp,sp
mov r5,r0 @ array address
mov r2,#0 @ indice array
1:
ldr r3,[r5,r2,lsl #2] @ load line pointer
mov r4,#0 @ line character indice
mov r7,#0 @ output buffer character indice
mov r6,#0 @ word length
mov r8,r3 @ word begin address
2: @ compute word length
ldrb r0,[r3,r4] @ load a character line
cmp r0,#0 @ line end ?
beq 3f
cmp r0,#'$' @ separator ?
beq 3f
add r4,r4,#1 @ increment line indice
add r6,r6,#1 @ increment word length
b 2b
3:
cmp r6,#0
beq 5f
sub r6,r1,r6 @ total spaces number to add
mov r12,r6
lsr r6,r6,#1 @ divise by 2 = left spaces number
4:
cmp r6,#0
blt 5f
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r7,r7,#1 @ increment output indice
sub r6,r6,#1 @ decrement number space
b 4b @ and loop
5:
mov r9,#0
6: @ copy loop word to buffer
ldrb r0,[r8,r9]
cmp r0,#'$' @ séparator ?
beq 7f
cmp r0,#0 @ line end ?
beq 10f
strb r0,[fp,r7]
add r7,r7,#1
add r9,r9,#1
b 6b
7:
lsr r6,r12,#1 @ divise total spaces by 2
sub r6,r12,r6 @ and compute number spaces to right side
8: @ loop to add right spaces
cmp r6,#0
ble 9f
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r7,r7,#1
sub r6,r6,#1
b 8b @ and loop
 
9:
add r8,r8,r9
add r8,r8,#1 @ new address word begin
mov r6,#0 @ raz word length
add r4,r4,#1 @ increment line indice
b 2b @ and loop new word
10:
mov r0,#'\n'
strb r0,[fp,r7] @ return line
add r7,r7,#1
mov r0,#0
strb r0,[fp,r7] @ final zéro
mov r0,fp
bl affichageMess @ display output buffer
add r2,r2,#1 @ increment line indice
cmp r2,#NBLINES @ maxi ?
blt 1b @ loop
100:
add sp,sp,#BUFFERSIZE
pop {r4-r12,pc}
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
LEFT :
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.
 
RIGHT :
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.
 
CENTER :
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.
</pre>
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">text: {
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 1,190 ⟶ 2,018:
}
 
output: map split.lines text => [split.by:"$" &]
 
loop output 'line [
loop line 'word -> prints pad word 12
print ""
]</langsyntaxhighlight>
 
{{out}}
Line 1,208 ⟶ 2,036:
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">Alignment := "L" ; Options: L, R, C
Text =
( LTrim
Line 1,256 ⟶ 2,084:
Return Ret
}
</syntaxhighlight>
</lang>
 
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
<lang AutoIt>
; == If the given text is in an file, it will read with:
#include <File.au3>
Line 1,343 ⟶ 2,171:
EndSwitch
EndFunc ;==>_GetAligned
</syntaxhighlight>
</lang>
Example output in Alignment: left - center - right - left - center - right - left - center - right - left - center - right
<pre>
Line 1,355 ⟶ 2,183:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f ALIGN_COLUMNS.AWK ALIGN_COLUMNS.TXT
BEGIN {
Line 1,397 ⟶ 2,225:
}
function max(x,y) { return((x > y) ? x : y) }
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 1,434 ⟶ 2,262:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">
DECLARE in$[] = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", \
"are$delineated$by$a$single$'dollar'$character,$write$a$program", \
Line 1,469 ⟶ 2,297:
Print_In_Columns(1)
Print_In_Columns(2)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,499 ⟶ 2,327:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DATA 6
DATA "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
DATA "are$delineated$by$a$single$'dollar'$character,$write$a$program"
Line 1,554 ⟶ 2,382:
WHEN "right": = STRING$(field%-LEN(word$), " ") + word$
ENDCASE
= word$</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="basic">10 rem ********************************
20 rem print words in columns
30 rem commodore basic 2.0
Line 1,622 ⟶ 2,450:
640 data "column$are$separated$by$at$least$one$space."
650 data "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
660 data "justified,$right$justified,$or$center$justified$within$its$column"</langsyntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
mode con cols=103
Line 1,708 ⟶ 2,536:
)
endlocal & set %~2=%len%
exit /b</langsyntaxhighlight>
{{out}}
<pre>Given a text file of many lines where fields within a line
Line 1,732 ⟶ 2,560:
 
=={{header|Beads}}==
<langsyntaxhighlight lang="beads">beads 1 program 'Align columns'
const
Line 1,784 ⟶ 2,612:
log "\n{v} justified\n"
div_line
show_table(v)</langsyntaxhighlight>
 
{{out}}
Line 1,836 ⟶ 2,664:
=={{header|BQN}}==
A function which returns a rectangular 2D array which represents the lines.
<langsyntaxhighlight lang="bqn">Split ← (⊢-˜+`׬)∘=⊔⊢
PadRow ← {
w‿t𝕊𝕩: # t → type.
Line 1,847 ⟶ 2,675:
Align ← {{𝕨∾' '∾𝕩}´˘⍉" "‿𝕨⊸PadRow˘⍉>⟨""⟩‿0 PadRow '$' Split¨(@+10) Split 𝕩}
 
1 Align text</langsyntaxhighlight>
<langsyntaxhighlight lang="bqn">┌─
╵" Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
Line 1,855 ⟶ 2,683:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. "
┘</langsyntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=dGV4dOKGkCJHaXZlbiRhJHRleHQkZmlsZSRvZiRtYW55JGxpbmVzLCR3aGVyZSRmaWVsZHMkd2l0aGluJGEkbGluZSQKYXJlJGRlbGluZWF0ZWQkYnkkYSRzaW5nbGUkJ2RvbGxhcickY2hhcmFjdGVyLCR3cml0ZSRhJHByb2dyYW0KdGhhdCRhbGlnbnMkZWFjaCRjb2x1bW4kb2YkZmllbGRzJGJ5JGVuc3VyaW5nJHRoYXQkd29yZHMkaW4kZWFjaCQKY29sdW1uJGFyZSRzZXBhcmF0ZWQkYnkkYXQkbGVhc3Qkb25lJHNwYWNlLgpGdXJ0aGVyLCRhbGxvdyRmb3IkZWFjaCR3b3JkJGluJGEkY29sdW1uJHRvJGJlJGVpdGhlciRsZWZ0JApqdXN0aWZpZWQsJHJpZ2h0JGp1c3RpZmllZCwkb3IkY2VudGVyJGp1c3RpZmllZCR3aXRoaW4kaXRzJGNvbHVtbi4iCgpTcGxpdCDihpAgKOKKoi3LnCtgw5fCrCniiJg94oqU4oqiClBhZFJvdyDihpAgewogIHfigL908J2VivCdlak6ICMgdCDihpIgdHlwZS4KICAgICAgICAjIDAg4oaSIGxlZnQKICAgICAgICAjIDEg4oaSIHJpZ2h0CiAgICAgICAgIyAyIOKGkiBjZW50ZXIKIHBzdHlsZeKGkHTiipHin6h7MOKAv/Cdlal9LHvwnZWp4oC/MH0se+KfqOKMivCdlanDtzIs4oyI8J2VqcO3MuKfqX3in6kKIPCdlal7KOKKo+KIvvCdlajiiL7iiqIpwrQoUHN0eWxlIPCdlakpL8KoPHd9wqgo4oyIwrQt4oqiKeKJoMKo8J2VqQp9CkFsaWduIOKGkCB7e/CdlajiiL4nICfiiL7wnZWpfcK0y5jijYkiICLigL/wnZWo4oq4UGFkUm93y5jijYk+4p+oIiLin6nigL8wIFBhZFJvdyAnJCcgU3BsaXTCqChAKzEwKSBTcGxpdCDwnZWpfQoKMSBBbGlnbiB0ZXh0CgoK Try It!]
 
Line 1,861 ⟶ 2,689:
See [[Column Aligner/C]]
 
=={{header|C sharp|C#}}==
===Old version===
Uses a delegate, which were added to the language in C# 2, to define left-, right-, or center-justified.
Line 1,867 ⟶ 2,695:
{{works with|C sharp|C#|2+}}
 
<langsyntaxhighlight lang="csharp">using System;
class ColumnAlignerProgram
{
Line 1,940 ⟶ 2,768:
}
}
}</langsyntaxhighlight>
 
===Newer version===
Line 1,946 ⟶ 2,774:
 
{{works with|C sharp|C#|8+}}
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,997 ⟶ 2,825:
}
 
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 2,028 ⟶ 2,856:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(ns rosettacode.align-columns
(:require [clojure.contrib.string :as str]))
Line 2,070 ⟶ 2,898:
 
(print-table (aligned-table table :center))
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">
identification division.
program-id. AlignColumns.
Line 2,157 ⟶ 2,985:
end-perform
.
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
------------------------------------------------------------------------------------------------------------------------
Given a text file of many lines, where fields within a line
Line 2,181 ⟶ 3,009:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
pad = (n) ->
s = ''
Line 2,233 ⟶ 3,061:
console.log "\n----- #{alignment}"
align input, alignment
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
> coffee align_columns.coffee
 
Line 2,261 ⟶ 3,089:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun nonempty (seq)
(position-if (lambda (x) (declare (ignore x)) t) seq))
 
Line 2,311 ⟶ 3,139:
(format s "~~~d~a<~~a~~>" (1+ w) fmtmod))
(princ "~}~%~}" s))
fields))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.string, std.algorithm, std.range, std.typetuple;
 
Line 2,335 ⟶ 3,163:
writefln("%-(%s %)", line.length.iota
.map!(i => just(line[i], maxWidths[i], ' ')));
}</langsyntaxhighlight>
{{out}}
<pre>Given a txt file of many lines, where fields within a line
Line 2,358 ⟶ 3,186:
=={{header|Delphi}}==
{{libheader|Delphi StdCtrls, Classes, SysUtils, StrUtils, Contnrs}}
<syntaxhighlight lang="delphi">
<lang Delphi>
USES
StdCtrls, Classes, SysUtils, StrUtils, Contnrs;
Line 2,415 ⟶ 3,243:
END;
end;
</syntaxhighlight>
</lang>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
 
def left(width, word) {
Line 2,447 ⟶ 3,275:
} + "\n"
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def text := "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$
Line 2,478 ⟶ 3,306:
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.</langsyntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|AWK}}
 
<syntaxhighlight>
global width inp$[] .
proc read . .
repeat
inp$ = input
until inp$ = ""
inp$[] &= inp$
ar$[] = strsplit inp$ "$"
for s$ in ar$[]
width = higher width len s$
.
.
.
read
#
proc out mode . .
for inp$ in inp$[]
ar$[] = strsplit inp$ "$"
for s$ in ar$[]
spc = width - len s$ + 1
if mode = 1
write s$
for i to spc
write " "
.
elif mode = 2
for i to spc
write " "
.
write s$
elif mode = 3
for i to spc div 2
write " "
.
write s$
for i to spc - spc div 2
write " "
.
.
.
print ""
.
.
out 1
print ""
out 2
print ""
out 3
#
input_data
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.
 
</syntaxhighlight>
 
=={{header|Elixir}}==
Line 2,485 ⟶ 3,375:
The String module of Elixir doesn't have the function of the center position adjusting.
It calls and processes the function of 'Erlang'.
<langsyntaxhighlight lang="elixir">defmodule Align do
def columns(text, alignment) do
fieldsbyrow = String.split(text, "\n", trim: true)
Line 2,519 ⟶ 3,409:
IO.puts "\n# #{alignment} Column-aligned output:"
Align.columns(text, alignment)
end)</langsyntaxhighlight>
 
{{out}}
Line 2,549 ⟶ 3,439:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module (align_columns).
Line 2,587 ⟶ 3,477:
Zipped = lists:zip (All_words, Words_length),
[ apply(string, Alignment, [Word, Length + 1, $\s])
|| {Word, Length} <- Zipped]. </langsyntaxhighlight>
 
{{out}}
Line 2,620 ⟶ 3,510:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant data = {
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
Line 2,680 ⟶ 3,570:
end for
puts(1,'\n')
end for</langsyntaxhighlight>
 
{{out}}
Line 2,707 ⟶ 3,597:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open System.IO
 
Line 2,739 ⟶ 3,629:
format table align
printfn "%s" (new String('-', (Array.sum width) + width.Length - 1))
0</langsyntaxhighlight>
Output, when called with a file containing the sample input
<pre>Given a text file of many lines, where fields within a line
Line 2,764 ⟶ 3,654:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: fry io kernel math math.functions math.order sequences
splitting strings ;
IN: rosetta.column-aligner
Line 2,803 ⟶ 3,693:
: print-aligned ( text alignment -- )
[ split-and-pad flip ] dip align-columns flip
[ [ write " " write ] each nl ] each ;</langsyntaxhighlight>
 
example-text { +left+ +middle+ +right+ } [ print-aligned ] with each
Line 2,809 ⟶ 3,699:
=={{header|FBSL}}==
Using a multiline string:
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
DIM s = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 2,843 ⟶ 3,733:
NEXT
 
PAUSE</langsyntaxhighlight>
{{out}}
Given a text file of many lines, where fields within a line
Line 2,856 ⟶ 3,746:
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">\ align columns
 
: split ( addr len char -- addr len1 addr len-len1 )
Line 2,925 ⟶ 3,815:
\ cleanup
nip free throw
column-widths free throw</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 2,943 ⟶ 3,833:
 
Given a FORMAT text that produces output in aligned columns makes it easy enough to meet the other requirements. To cause texts to be aligned left, append sufficient spaces to each output text, and for centred text, half that number. This relies on the special intrinsic function REPEAT(text,n) returning a varying number of characters - CHARACTER functions have to return a ''fixed'' number of characters, until the standardisation of varying-length strings in F2003 ''et seq''. Earlier Fortrans lack the REPEAT function, but its effect can be gained via something like CHARACTER*66 SPACE, where SPACE is set to spaces, and SPACE(1:N) is used where REPEAT(" ",N) is desired. And if messing with variable FORMAT is unwanted, the REPEAT scheme can be used for the right-justified output also.
<syntaxhighlight lang="fortran">
<lang Fortran>
SUBROUTINE RAKE(IN,M,X,WAY) !Casts forth text in fixed-width columns.
Collates column widths so that each column is wide enough for its widest member.
Line 3,038 ⟶ 3,928:
CALL RAKE(IN,M,"$",+1) !Align right.
END !That's all.
</syntaxhighlight>
</lang>
Every line of output starts with a space, and if it were to be sent to a lineprinter, this would be used as the carriage control character (meaning, advance one line then print the rest) - the first column does not need to be set off by one space from the previous column, but rather than devise special treatment it is spaced off anyway. The free-format output statements also start with a space. Output:
<pre>
Line 3,072 ⟶ 3,962:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub Split(s As String, sep As String, result() As String)
Line 3,169 ⟶ 4,059:
Next i
 
Close #1 : Close #2 : Close #3</langsyntaxhighlight>
 
{{out}}
Line 3,207 ⟶ 4,097:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
 
 
=={{header|FutureBasic}}==
Note: FB's NSLog, used for demonstrations, does not have a center alignment provision. However FB allows advanced alignment and text formatting in normal application development. Simple right and left alignment are shown here.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn AlignColumn
NSUInteger i
CFStringRef testStr = @"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."
CFArrayRef temp = fn StringComponentsSeparatedByString( testStr, @"$" )
CFMutableArrayRef arr = fn MutableArrayWithArray( temp )
NSUInteger count = fn ArrayCount( arr )
ptr a(50)
NSLog( @"\nLeft aligned:\n" )
NSUInteger lineCheck = 1
for i = 0 to count -1
a( lineCheck ) = (ptr)fn StringUTF8String( arr[i] )
if ( lineCheck == 9 )
NSLog( @"%-12s %-11s %-12s %-11s %-12s %-12s %-12s %-12s %-12s", a(1),a(2),a(3),a(4),a(5),a(6),a(7),a(8),a(9) )
lineCheck = 1
else
lineCheck++
end if
next
NSLog( @"\n\nRight aligned:\n" )
lineCheck = 1
for i = 0 to count -1
a( lineCheck ) = (ptr)fn StringUTF8String( arr[i] )
if ( lineCheck == 9 )
NSLog( @"%12s %11s %12s %11s %12s %12s %12s %12s %12s", a(1),a(2),a(3),a(4),a(5),a(6),a(7),a(8),a(9) )
lineCheck = 1
else
lineCheck++
end if
next
end fn
 
fn AlignColumn
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
 
Left aligned:
 
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.
 
 
Right aligned:
 
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.
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=023b4c5144d45e047abe02ebf5c4525a Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main() 'Written in Gambas 3.9.2 as a Command line Application - 15/03/2017
Dim siCount, siCounter, siLength As Short 'Counters
Dim siLongest As Short = -1 'To store the longest 'Word'
Line 3,254 ⟶ 4,219:
Next
 
End</langsyntaxhighlight>
 
{{out}}
Line 3,281 ⟶ 4,246:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,341 ⟶ 4,306:
f.print(middle)
f.print(right)
}</langsyntaxhighlight>
<pre>
Given a text file of many lines, where fields within a line
Line 3,367 ⟶ 4,332:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def alignColumns = { align, rawText ->
def lines = rawText.tokenize('\n')
def words = lines.collect { it.tokenize(/\$/) }
Line 3,380 ⟶ 4,345:
 
words.each { padAll(justify[align], columnWidths, it).each { print it }; println() }
}</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight lang="groovy">def rawTextInput = '''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$
Line 3,394 ⟶ 4,359:
alignColumns(align, rawTextInput)
println()
}</langsyntaxhighlight>
 
{{out}}
Line 3,423 ⟶ 4,388:
=={{header|Harbour}}==
 
<langsyntaxhighlight lang="visualfoxpro">
PROCEDURE Main()
LOCAL a := { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",;
Line 3,464 ⟶ 4,429:
RETURN
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="text">----Left aligned columns----
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
Line 3,488 ⟶ 4,453:
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.</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr, transpose)
import Control.Arrow (second)
 
Line 3,516 ⟶ 4,481:
where
dl = cw - length w
(l, r) = (dl `div` 2, dl - l)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,530 ⟶ 4,495:
Or, using '''Text''' and its functions as an alternative to '''[Char]''' strings:
 
<langsyntaxhighlight lang="haskell">import Prelude as P
import Data.Text as T
(Text, pack, unpack, splitOn, unlines, unwords, length,
Line 3,564 ⟶ 4,529:
(zip cols ((T.length . maximumBy (comparing T.length)) <$> cols))
] <*>
[justifyLeft, justifyRight, center]</langsyntaxhighlight>
{{Out}}
<pre>Given a text file of many lines, where fields within a line
Line 3,589 ⟶ 4,554:
=={{header|HicEst}}==
A file opened with a Format option describing the column format(s) can be addressed like a standard in-memory array. In addition the DLG function ([http://www.HicEst.com/MatrixExplorer.htm MatrixExplorer]) allows this text/numeric file to be edited or visualized in many ways, but string columns are always left adjusted while numeric columns are right adjusted. Export is possible.
<syntaxhighlight lang="hicest">
<lang HicEst>
CHARACTER Fnam = "\HicEst\Rosetta\Align columns.txt"
 
Line 3,616 ⟶ 4,581:
WRITE() out
ENDDO
END</langsyntaxhighlight>
<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
Line 3,639 ⟶ 4,604:
An argument of <tt>left</tt>, <tt>center</tt>, or <tt>right</tt> controls the
column alignment. The default is left-alignment.
<langsyntaxhighlight lang="icon">global width
 
procedure main(args)
Line 3,668 ⟶ 4,633:
write()
}
end</langsyntaxhighlight>
 
Sample run:
Line 3,681 ⟶ 4,646:
 
=={{header|J}}==
Here, we rely on J's built-in formatting mechanism for boxed arrays, with spaces to separate the columns.
 
(J's [[j:Vocabulary/Foreigns#m9|9!:n]] series of conjunctions queries (even) or sets (odd) session parameters. 9!:6 queries the box display characters, and 9!:7 sets them. Here, we use spaces with 9!:7 (discarding the blank rows). Meanwhile 9!:17 determines whether box contents are left justified, center justified or right justified, and we also use that. There's some additional discussion of this approach on the [[Talk:Align_columns#J_solution|talk page]].)
 
 
'''Solution'''
<langsyntaxhighlight lang="j">'LEFT CENTER RIGHT'=: i.3 NB. justification constants
NB.* alignCols v Format delimited text in justified columns
Line 3,699 ⟶ 4,669:
7 17 global oldbox NB. restore settings
result
)</langsyntaxhighlight>
 
'''Example''':
<langsyntaxhighlight lang="j"> text=: noun define
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 3,725 ⟶ 4,695:
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.</langsyntaxhighlight>
 
=={{header|Java}}==
Line 3,732 ⟶ 4,702:
{{libheader|Apache Commons Lang}}
 
<langsyntaxhighlight Javalang="java">import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
Line 3,875 ⟶ 4,845:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,881 ⟶ 4,851:
===Imperative===
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
var justification="center",
input=["Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
Line 3,912 ⟶ 4,882:
for(x=0;x<input.length;x++) input[x]=input[x].join(" ");
input=input.join("\n");
document.write(input);</langsyntaxhighlight>
 
===Functional===
 
<langsyntaxhighlight JavaScriptlang="javascript">//break up each string by '$'. The assumption is that the user wants the trailing $.
var data = [
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
Line 3,963 ⟶ 4,933:
 
return zip(formattedCols).map(function (row) { return row.join(' '); }).join('\n');
};</langsyntaxhighlight>
 
 
Line 3,969 ⟶ 4,939:
Or (ES5) using transpose and zipWith:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (strText) {
'use strict';
Line 4,101 ⟶ 5,071:
Further,$allow$for$each$word$in$a$column$to$be$either$left$\n\
justified,$right$justified,$or$center$justified$within$its$column."
);</langsyntaxhighlight>
 
{{Out}}
Line 4,129 ⟶ 5,099:
{{ Works with|jq|1.4}}
The key to the following implementation is the filter named "transpose", which is defined to work on a possibly jagged matrix. It is provided as a built-in in jq 1.5 and later.
<langsyntaxhighlight lang="jq"># transpose a possibly jagged matrix
def transpose:
if . == [] then []
Line 4,171 ⟶ 5,141:
(""; . + ($line[$i]|justify($widths[$i])) ))
| join("\n")
;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">"Center:", format("center"), "",
"Left:", format("left"), "",
"Right:", format("right")</langsyntaxhighlight>
{{Out}}
<div style="overflow:scroll; height:200px;"><langsyntaxhighlight lang="sh">$ jq -M -R -r -s -f Align_columns.jq Align_columns.txt
Center:
Given a text file of many lines, where fields within a line
Line 4,201 ⟶ 5,171:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</langsyntaxhighlight></div>
 
=={{header|Jsish}}==
From Javascript ES5 entry.
<langsyntaxhighlight lang="javascript">/* Align columns, in Jsish */
function alignColumns(phrases:array, just:string) {
var x, y, max, diff, left, right, cols=0;
Line 4,246 ⟶ 5,216:
puts(alignColumns(trial, just), '\n');
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,276 ⟶ 5,246:
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang="julia">txt = """Given\$a\$txt\$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\$
Line 4,315 ⟶ 5,285:
end
println("-"^sum(max_widths))
end</langsyntaxhighlight>
{{out}}
<pre>
Line 4,345 ⟶ 5,315:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
Line 4,407 ⟶ 5,377:
else -> System.err.println("Error! Unknown alignment: " + alignment)
}
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
Line 4,413 ⟶ 5,383:
The input data is a sequence of characters where words are supposed to be separated by $ and lines be ended by \$. A HTML table is used to format the output left, centered or right justified.
 
<langsyntaxhighlight lang="scheme">
{def txt
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.}
Line 4,452 ⟶ 5,422:
 
{columns center txt} and {columns right txt} outputs can be seen in this website: http://lambdaway.free.fr/lambdawalks/?view=align_columns
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
local(text = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 4,521 ⟶ 5,491:
}
 
prepcols(#text)</langsyntaxhighlight>
 
{{out}}
Line 4,552 ⟶ 5,522:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">mainwin 140 32
 
CRLF$ =chr$( 13)
Line 4,629 ⟶ 5,599:
end function
 
end</langsyntaxhighlight>
 
=={{header|Lua}}==
{{works with|Lua|5.1}}
 
<langsyntaxhighlight lang="lua">
local tWord = {} -- word table
local tColLen = {} -- maximum word length in a column
Line 4,695 ⟶ 5,665:
return output
end--alignColumn
</syntaxhighlight>
</lang>
 
Usage Example:
 
<langsyntaxhighlight lang="lua">
input =
[[Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 4,712 ⟶ 5,682:
outputRight = alignColumn(input, "right")
alignColumn(input, "center", "output.txt")
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Align_Columns {
a$={Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 4,768 ⟶ 5,738:
}
Align_Columns
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,794 ⟶ 5,764:
=={{header|Maple}}==
Assign the sample data.
<syntaxhighlight lang="maple">
<lang Maple>
txt :=
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
Line 4,802 ⟶ 5,772:
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"justified,$right$justified,$or$center$justified$within$its$column.\n":
</syntaxhighlight>
</lang>
The following procedure solves the problem. It takes the string to be operated on as input, and an optional alignment parameter, which defaults to centred alignment. The aligned text is returned, as a string, which can then be printed.
<syntaxhighlight lang="maple">
<lang Maple>
AlignColumns := proc( txt, align :: { "left", "right", "centre" } := "centre" )
uses StringTools;
Line 4,829 ⟶ 5,799:
Join( J, "\n" )
end proc:
</syntaxhighlight>
</lang>
For the sample text, we get the following results.
<syntaxhighlight lang="maple">
<lang Maple>
> printf( "%s\n", AlignColumns( txt ) ):
Given a text file of many lines, where fields within a line
Line 4,860 ⟶ 5,830:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
</lang>
Alternatively, this could be printed to a file (using fprintf instead of printf).
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">TableForm[StringSplit[StringSplit[a,"\n"],"$"],TableAlignments -> Center]</langsyntaxhighlight>
Output with example text :
[[File:centeredtext.png]]
Line 4,870 ⟶ 5,840:
=={{header|MATLAB}} / {{header|Octave}}==
center-justified formatting is not implemented here
<syntaxhighlight lang="matlab">
<lang Matlab>
function r = align_columns(f)
fid = fopen('align_column_data.txt', 'r');
Line 4,900 ⟶ 5,870:
end
end;
</syntaxhighlight>
</lang>
 
 
Line 4,920 ⟶ 5,890:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
Alignment = {"left": -1, "center": 0, "right": 1}
 
Align = {}
Align.load = function(contents)
self.lines = contents.split(char(13))
self.rows = []
self.numColumns = 0
for line in self.lines
columns = line.split("$")
if columns.len > self.numColumns then self.numColumns = columns.len
self.rows.push(columns)
end for
self.widths = []
for col in range(0, self.numColumns - 1)
maxWidth = 0
for line in self.rows
if col > line.len - 1 then continue
if line[col].len > maxWidth then maxWidth = line[col].len
end for
self.widths.push(maxWidth)
end for
end function
 
Align.__getField = function(word, width, alignment)
if alignment == Alignment.left then return (word + " " * width)[:width]
if alignment == Alignment.right then return (" " * width+word)[-width:]
if alignment == Alignment.center then
leftMargin = floor((width - word.len) / 2)
return (" " * leftMargin + word + " " * width)[:width]
end if
end function
 
Align.output = function(alignment)
for line in self.rows
for c in range(0, line.len - 1)
print self.__getField(line[c], self.widths[c], alignment) + " ", ""
end for
print
end for
end function
 
txt = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" + char(13)
txt += "are$delineated$by$a$single$'dollar'$character,$write$a$program" + char(13)
txt += "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" + char(13)
txt += "column$are$separated$by$at$least$one$space." + char(13)
txt += "Further,$allow$for$each$word$in$a$column$to$be$either$left$" + char(13)
txt += "justified,$right$justified,$or$center$justified$within$its$column."
 
Align.load(txt)
print "Left alignment:"
Align.output(Alignment.left)
print
print "Right alignment:"
Align.output(Alignment.right)
print
print "Centered: "
Align.output(Alignment.center)
</syntaxhighlight>
 
 
{{out}}
<pre>
>miniscript.exe align-columns.ms
Left alignment:
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.
 
Right alignment:
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.
 
Centered:
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.
</pre>
 
Line 4,926 ⟶ 5,987:
Note the presetting of P102 to indicate the alignment required.
 
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" Align columns - assumes macros on input stream 1, data on stream 2
MCPVAR 102
Line 4,982 ⟶ 6,043:
>
MCSET S1=1
*MCSET S10=102</langsyntaxhighlight>
 
=={{header|ML/I}}==
Line 4,988 ⟶ 6,049:
Note the presetting of P102 to indicate the alignment required.
 
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" Align columns - assumes macros on input stream 1, data on stream 2
MCPVAR 102
Line 5,044 ⟶ 6,105:
>
MCSET S1=1
*MCSET S10=102</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">columns(how) ; how = "Left", "Center" or "Right"
New col,half,ii,max,spaces,word
Set ii=0
Line 5,099 ⟶ 6,160:
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.</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">from strutils import splitLines, split
from sequtils import mapIt
from strfmt import format, write
Line 5,126 ⟶ 6,187:
stdout.write(w.format align & $maxs[j])
stdout.write "\n"
stdout.write "\n"</langsyntaxhighlight>
{{out}}
<pre>Left column-aligned output:
Line 5,156 ⟶ 6,217:
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/align_columns.nit the official Nit’s repository]
 
<langsyntaxhighlight lang="nit"># Task: Align columns
#
# Uses `Text::justify` from the standard library.
Line 5,204 ⟶ 6,265:
aligner(text, 0.0)
aligner(text, 1.0)
aligner(text, 0.5)</langsyntaxhighlight>
{{out}}
<pre>Given a text file of many lines, where fields within a line
Line 5,228 ⟶ 6,289:
=={{header|Oberon-2}}==
works with oo2c version 2.
<langsyntaxhighlight lang="oberon2">
MODULE Columns;
IMPORT
Line 5,337 ⟶ 6,398:
END Columns.
 
</syntaxhighlight>
</lang>
<pre>
Given a text file of many lines, where fields within a line
Line 5,364 ⟶ 6,425:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#load "str.cma"
open Str
 
Line 5,417 ⟶ 6,478:
let sp2 = String.make pad2 ' ' in
Printf.printf "%s%s%s " sp1 word sp2);
;;</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight lang="oforth">import: mapping
import: file
 
Line 5,441 ⟶ 6,502:
0 #[ apply( #[ size max ] ) ] lines apply ->maxsize
#[ apply( #[ justify( maxsize , just) . ] ) printcr ] lines apply
;</langsyntaxhighlight>
 
{{out}}
Line 5,457 ⟶ 6,518:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
text = .array~of("Given$a$text$file$of$many$lines,$where$fields$within$a$line$", -
"are$delineated$by$a$single$'dollar'$character,$write$a$program", -
Line 5,532 ⟶ 6,593:
say out~string
end
</syntaxhighlight>
</lang>
<pre>
align left:
Line 5,563 ⟶ 6,624:
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">FUNCTION alignColumns RETURNS CHAR (
i_c AS CHAR,
i_calign AS CHAR
Line 5,622 ⟶ 6,683:
alignColumns( cc, "right" ) SKIP
alignColumns( cc, "center" )
VIEW-AS ALERT-BOX.</langsyntaxhighlight>
 
{{out}}
Line 5,787 ⟶ 6,848:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
%% Lines: list of strings
%% Alignment: function like fun {Left Txt ExtraSpace} ... end
Line 5,861 ⟶ 6,922:
"justified,$right$justified,$or$center$justified$within$its$column."]
in
{ForAll {Align Lines Left} System.showInfo}</langsyntaxhighlight>
 
=={{header|Pascal}}==
See [[Align_columns#Delphi | Delphi]]
modified to {{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">program Project1;
 
{$H+}//Use ansistrings
Line 5,939 ⟶ 7,000:
AlignByColumn(taCenter);
AlignByColumn(taRightJustify);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 5,965 ⟶ 7,026:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#/usr/bin/perl -w
use strict ;
 
Line 6,020 ⟶ 7,081:
}
print "\n" ;
}</langsyntaxhighlight>
a shorter solution
<langsyntaxhighlight lang="perl">use List::Util qw(max);
 
sub columns {
Line 6,045 ⟶ 7,106:
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
END</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">data</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
<span style="color: #008000;">"Given$a$text$file$of$many$lines,$where$fields$within$a$line$"</span><span style="color: #0000FF;">,</span>
Line 6,116 ⟶ 7,177:
<span style="color: #000000;">AlignColumns</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 6,142 ⟶ 7,203:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
0 40 repeat var gap
Line 6,187 ⟶ 7,248:
0 alignWords nl
1 alignWords nl
drop</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
Line 6,236 ⟶ 7,297:
echo aligner($textinfile, $j);
 
?></langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
 
main =>
Text =
"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.",
Lines = split(Text,"\n"),
Lines = [Line1|_],
N = len(split(strip(Line1,"$ "), "$")), % number of columns
WidthArr = {0 : _ in 1..N},
foreach (Line in Lines)
Words = split(strip(Line,"$ "), "$"),
foreach ({I,Word} in zip(1..N, Words))
WidthArr[I] := max(WidthArr[I], len(Word))
end
end,
foreach (I in 1..N)
WidthArr[I] := WidthArr[I]+1 % separate cols by at least one space
end,
foreach (Align in [left, right, center])
output_lines(Lines,N,WidthArr,Align),
nl,nl
end.
 
output_lines(Lines,N,WidthArr,Align) =>
foreach (Line in Lines)
Words = split(strip(Line,"$ "), "$"),
foreach ({I,Word} in zip(1..N, Words))
output_word(Word,WidthArr[I],Align)
end,
nl
end.
 
output_word(Word,Width,left) =>
printf("%-*s",Width,Word).
output_word(Word,Width,right) =>
printf("%*s",Width,Word).
output_word(Word,Width,_) =>
Pad = len(Word)-Width,
Pad1 is Pad div 2,
Pad2 is Pad-Pad1,
printf("%*s%s%*s",Pad1,"",Word,Pad2,"").
</syntaxhighlight>
{{out}}
<pre>
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.
 
 
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.
 
 
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.
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Sizes NIL # Build a list of sizes
(let Lines # and of lines
(make
Line 6,259 ⟶ 7,394:
(prinl)
(for L Lines
(prinl (apply center L Sizes)) ) ) ) # and centered</langsyntaxhighlight>
{{out}}
<pre>Given a text file of many lines, where fields within a line
Line 6,283 ⟶ 7,418:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare text character (300) varying;
declare word character (20) varying;
Line 6,321 ⟶ 7,456:
put file (output) skip;
end;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$file =
@'
Line 6,347 ⟶ 7,482:
}
$arr | Format-Table -HideTableHeaders -Wrap *
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 6,360 ⟶ 7,495:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">aligner :-
L ="Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 6,439 ⟶ 7,574:
{N2 is N1 + 1},
parse_word(T, N2, NF, TF).
</syntaxhighlight>
</lang>
 
{{out}}
Line 6,471 ⟶ 7,606:
=={{header|PureBasic}}==
{{works with|PureBasic|4.41}}
<langsyntaxhighlight PureBasiclang="purebasic">Declare max(a,b)
 
If OpenConsole()
Line 6,545 ⟶ 7,680:
Data.s "Further,$allow$for$each$word$in$a$column$oo$be$either$left$"
Data.s "justified,$right$justified,$or$center$justified$within$its$column."
EndDataSection</langsyntaxhighlight>
 
=={{header|Python}}==
===Procedural===
====Using f-strings====
<langsyntaxhighlight lang="python">from itertools import zip_longest
 
txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
Line 6,569 ⟶ 7,704:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
</syntaxhighlight>
</lang>
 
{{out}}
Line 6,601 ⟶ 7,736:
 
====Using StringIO====
<langsyntaxhighlight lang="python">from StringIO import StringIO
textinfile = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 6,645 ⟶ 7,780:
infile = StringIO(textinfile)
print "\n# %s Column-aligned output:" % align
print aligner(infile, align[0])</langsyntaxhighlight>
 
{{out}}
Line 6,676 ⟶ 7,811:
Works with Python 2 and 3.
 
<langsyntaxhighlight lang="python">'''
cat <<'EOF' > align_columns.dat
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 6,693 ⟶ 7,828:
for row in rows:
print(' '.join(fmts).format(*(row + [''] * len(fmts))))
print('')</langsyntaxhighlight>
 
 
====Alternative====
{{trans|D}}
<langsyntaxhighlight lang="python">txt = """Given$a$txt$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$
Line 6,718 ⟶ 7,853:
print(justify(word, max_widths[j]), end=' ')
print()
print("- " * 52)</langsyntaxhighlight>
 
===Functional===
Line 6,726 ⟶ 7,861:
(Selection of string justification methods via '''getattr'''):
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Variously aligned columns
from delimited text.
'''
Line 6,800 ⟶ 7,935:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Given a text file of many lines, where fields within a line
Line 6,824 ⟶ 7,959:
 
=={{header|q}}==
<langsyntaxhighlight lang="q">text:(
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$";
"are$delineated$by$a$single$'dollar'$character,$write$a$program";
Line 6,837 ⟶ 7,972:
ps:$[aln=`R;-1-cw;1+cw]$''s; / padded strings
ps:$[aln=`C;(neg(cw-sl)div 2)rotate''ps;ps]; / center
1,[;"\n\n"]"\n"sv raze each ps; } / print</langsyntaxhighlight>
{{out}}
<pre>q)ta[`L]text
Line 6,865 ⟶ 8,000:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r"># Read in text
lines <- readLines(tc <- textConnection("Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 6,889 ⟶ 8,024:
print0(leftjust)
print0(rightjust)
print0(centrejust)</langsyntaxhighlight>
Right justified output shown.
<div style="width:full;overflow:scroll"><pre>
Line 6,901 ⟶ 8,036:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 6,936 ⟶ 8,071:
(display-aligned #:justify 'right text)
(display-aligned #:justify 'center text)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 6,944 ⟶ 8,079:
Call with parameter left (default), center or right.
 
<syntaxhighlight lang="raku" perl6line>my @lines =
q|Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 6,966 ⟶ 8,101:
default { $word ~ " " x $lr }
}
}</langsyntaxhighlight>
 
Or a more functional version, called like <code>./align.p6 left input.txt</code>, which however only supports left and right alignment (not center):
 
<syntaxhighlight lang="raku" perl6line>sub MAIN ($alignment where 'left'|'right', $file) {
my @lines := $file.IO.lines.map(*.split('$').cache).cache;
my @widths = roundrobin(|@lines).map(*».chars.max);
Line 6,976 ⟶ 8,111:
my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ "\n";
printf $format, |$_ for @lines;
}</langsyntaxhighlight>
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Line 7,021 ⟶ 8,156:
TextCenter = TextCenter + Newline
next
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:20ex;overflow:scroll">TextLeft contains:
Line 7,049 ⟶ 8,184:
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">REBOL [
Title: "Align Columns"
URL: http://rosettacode.org/wiki/Align_columns
Line 7,106 ⟶ 8,241:
foreach i [left centre right] [
print ["^/Align" i "...^/"] entable data get i]
</syntaxhighlight>
</lang>
 
{{out}}
Line 7,138 ⟶ 8,273:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red [
Title: "Align Columns"
Original-Author: oofoe
Line 7,196 ⟶ 8,331:
 
foreach i [left centre right] [
print [newline "Align" i "..." newline] entable data get i]</langsyntaxhighlight>
 
=={{header|REXX}}==
===(no output)===
<langsyntaxhighlight lang="rexx">/*REXX*/
z.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
z.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
Line 7,248 ⟶ 8,383:
end
say out
end</langsyntaxhighlight>
 
===(with output)===
<langsyntaxhighlight lang="rexx">/*REXX program displays various alignments for words in an array of text strings. */
size= 0; t.=; cols= 0; wid.= 0; @.= /*zero or nullify some variables. */
t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Line 7,280 ⟶ 8,415:
say substr(_, 2) /*ignore the leading extra blank. */
end /*r*/
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 7,312 ⟶ 8,447:
===(boxed output)===
Note: &nbsp; this version boxes each column of output to better show the columns.
<langsyntaxhighlight lang="rexx">/*REXX program displays various alignments for words in an array of text strings. */
size= 0; t.=; cols= 0; wid.= 0; @.= /*zero or nullify some variables. */
t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Line 7,348 ⟶ 8,483:
end /*r*/ /* [↑] shows words in boxes. */
say translate(bot, '┴', "┬") /*display the bottom line of the box. */
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 7,386 ⟶ 8,521:
=={{header|Ruby}}==
{{works with|Ruby|1.9.3+}}
<langsyntaxhighlight lang="ruby">J2justifier = {Left: :ljust, Right: :rjust, Center: :center}
 
=begin
Line 7,429 ⟶ 8,564:
puts aligner(infile, align)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 7,459 ⟶ 8,594:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">theString$ = "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$"_
Line 7,497 ⟶ 8,632:
wend
print
end function</langsyntaxhighlight>
{{out}}
<pre style="height:15ex;overflow:scroll">------------ align:left -- across:6 ------------
Line 7,537 ⟶ 8,672:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::iter::{repeat, Extend};
 
enum AlignmentType {
Line 7,600 ⟶ 8,735:
println!("{}", repeat('-').take(110).collect::<String>());
println!("{}", align_columns(text, AlignmentType::Right));
}</langsyntaxhighlight>
{{out}}
<pre style="height:15ex;overflow:scroll">
Line 7,632 ⟶ 8,767:
For Scala 2.7, change from fromPath to fromFile, and remove the extra parameter to Source's getLines.
 
<langsyntaxhighlight lang="scala">object ColumnAligner {
val eol = System.getProperty("line.separator")
def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)
Line 7,659 ⟶ 8,794:
alignFile(filename, alignment) foreach println
}
}</langsyntaxhighlight>
 
Another take:
 
<langsyntaxhighlight lang="scala">def pad(s:String, i:Int, d:String) = {
val padsize = (i-s.length).max(0)
d match {
Line 7,684 ⟶ 8,819:
val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
padded map (_.reduceLeft(_ + _)) foreach println</langsyntaxhighlight>
 
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 7,742 ⟶ 8,877:
(align-columns *example* 'center)
(align-columns *example* 'right)
</syntaxhighlight>
</lang>
 
{{out}}
Line 7,774 ⟶ 8,909:
=={{header|sed}}==
The code allows to left (by default) or right justify colums. Centering is not supported. Requires about 2x<size of input> bytes of memory (each line duplicated).
<langsyntaxhighlight lang="sed">
#!/bin/sed -nrf
# Format: <master-pattern>\n<line1>\n<line1-as-pattern>\n<line2>\n<line2-as-pattern>...
Line 7,850 ⟶ 8,985:
bnextline
}
</syntaxhighlight>
</lang>
Example:
<pre>
Line 7,870 ⟶ 9,005:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const array string: inputLines is [] (
Line 7,921 ⟶ 9,056:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 7,932 ⟶ 9,067:
justified, right justified, or center justified within its column.
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program align;
magic := false; $ turn off regexp matching in GNU SETL
read_file;
ncols := max/[#line : line in lines];
sizes := [1+max/[#(line(col) ? "") : line in lines] : col in [1..ncols]];
loop for line in lines do
print(+/[align(line(col), sizes(col)) : col in [1..#line]]);
end loop;
read_file::
f := open(command_line(1), "r");
lines := [];
loop doing geta(f, line); while line /= om do
lines with:= split(line, "$");
end loop;
close(f);
proc align(s, n);
case command_line(2) of
("r"): return lpad(s, n);
("l"): return rpad(s, n);
("c"): return center(s, n);
end case;
end proc;
proc center(s, n);
padding := n - #s;
l := " " * ceil(padding/2);
r := " " * floor(padding/2);
return l + s + r;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>$ setl align.setl test.txt l
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.
$ setl align.setl test.txt r
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.
$ setl align.setl test.txt c
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.</pre>
 
=={{header|Shiny}}==
<langsyntaxhighlight lang="shiny">text: '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$
Line 7,972 ⟶ 9,165:
align text 'left'
align text 'center'
align text 'right'</langsyntaxhighlight>
 
<pre>Given a text file of many lines, where fields within a line
Line 7,996 ⟶ 9,189:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Format(text, width) {
method align(j) {
text.map { |row|
Line 8,042 ⟶ 9,235:
say f.align(left);
say f.align(middle);
say f.align(right);</langsyntaxhighlight>
 
=={{Header|Smalltalk}}==
the following works with Smalltalk/X, but should also in other dialects (may have to add "centerPadded" to the String class).
{{works with |Smalltalk/X }}
<langsyntaxhighlight lang="smalltalk">text :=
'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$''dollar''$character,$write$a$program
Line 8,116 ⟶ 9,309:
 
Stdout cr; printCR:'Centered with box:'.
printCentered value:text value:true.</langsyntaxhighlight>
{{out}}
<pre>Left justified:
Line 8,189 ⟶ 9,382:
=={{header|Snobol}}==
{{works with|Snobol|4}}
<langsyntaxhighlight lang="snobol">* Since we don't know how much text we'll be reading in,
* we store the words and field widths in tables
Words = TABLE()
Line 8,281 ⟶ 9,474:
 
END
</syntaxhighlight>
</lang>
 
{{Out}}
Line 8,308 ⟶ 9,501:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
 
pragma annotate( summary, "aligncols" )
@( description, "Given a text file of many lines, where fields within a line are delineated ")
@( description, "by a single 'dollar' character, write a program that aligns each column of" )
@( description, "fields by ensuring that words in each column are separated by at least one" )
@( description, "space. Further, allow for each word in a column to be either left justified," )
@( description, "right justified, or center justified within its column. " )
@( description, "A modified version of the Ada solution from Rosetta Code" )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Align_columns" );
pragma license( unrestricted );
 
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
 
procedure aligncols is
Text : constant string :=
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & ASCII.NUL &
"are$delineated$by$a$single$'dollar'$character,$write$a$program" & ASCII.NUL &
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & ASCII.NUL &
"column$are$separated$by$at$least$one$space." & ASCII.NUL &
"Further,$allow$for$each$word$in$a$column$to$be$either$left$" & ASCII.NUL &
"justified,$right$justified,$or$center$justified$within$its$column." & ASCII.NUL;
File : file_type;
Width : array(1..1000) of natural;
ch : character;
Column : positive := 1;
Start : positive := 1;
type Alignment is ( Left, Center, Right );
s : string;
padding : natural;
begin
-- Zero Widths
for I in arrays.first( Width )..arrays.last( Width ) loop
Width(I) := 0;
end loop;
-- Determining the widths of columns
for I in 1..strings.length(Text) loop
ch := strings.element( Text, I );
case ch is
when '$' | ASCII.NUL =>
Width (Column) := numerics.max(Width (Column), I - Start + 1);
Start := I + 1;
if strings.element( Text, I ) = ASCII.NUL then
Column := 1;
else
Column := @+1;
end if;
when others =>
null;
end case;
end loop;
create( File, out_file, "columned.txt" );
-- Formatting
for Align in Left..Right loop
Column := 1;
Start := 1;
for I in 1..strings.length(Text) loop
ch := strings.element( Text, I );
case ch is
when '$' | ASCII.NUL =>
s := strings.slice( Text, Start, I-1 );
padding := (Width( Column ) - strings.length(s));
case Align is
when Left =>
s := @ & (padding * ' ');
when Center =>
declare
left_padding : constant natural := padding/2;
right_padding : constant natural := padding - left_padding;
begin
s := (left_padding * ' ') & @ & (right_padding * ' ');
end;
when Right =>
s := (padding * ' ') & @;
when others =>
null;
end case;
put( File, s );
Start := I+1;
if ch = ASCII.NUL then
new_line( File );
Column := 1;
else
Column := @+1;
end if;
when others =>
null;
end case;
end loop;
new_line( File );
end loop;
close( File );
end aligncols;</syntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun curry f x y = f (x, y)
fun uncurry f (x, y) = f x y
 
Line 8,338 ⟶ 9,630:
(* test stdin with all alignments *)
val () = print (String.concatWith "\n\n"
(map (formatTable (readTable TextIO.stdIn)) [alignL, alignC, alignR]) ^ "\n")</langsyntaxhighlight>
{{out}}
<pre>Given a text file of many lines, where fields within a line
Line 8,366 ⟶ 9,658:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">import Foundation
 
extension String {
Line 8,451 ⟶ 9,743:
print(alignCols(input: input, align: .center))
print()
print(alignCols(input: input, align: .right))</langsyntaxhighlight>
 
{{out}}
Line 8,479 ⟶ 9,771:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
set text {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 8,526 ⟶ 9,818:
}
puts ""
}</langsyntaxhighlight>
{{out}}
<pre>Given a text file of many lines, where fields within a line
Line 8,548 ⟶ 9,840:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
 
=={{header|Transd}}==
Transd has built-in support for "left" and "right" formatting, but not "centered", which added quite a bit of code.
 
<syntaxhighlight lang="scheme">#lang transd
 
MainModule : {
txt:
"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.",
tabl: Table(),
n: 0,
colWidths: Vector<Int>(),
 
print: (λ centered Bool(false)
(for n in Seq(0 (num-rows tabl)) do
(with row (get-row tabl n)
(for m in Seq(0 (num-cols tabl)) do
(with wid (+ 1.0 (get colWidths @idx))
word (get row m) wl 0.0 lef 0
(if centered (= wl (size String(word))) (= lef (/ (- wid wl) 2.0))
(textout width: lef "" width: wl word width: (- wid (+ wl lef)) "")
else
(textout width: wid (get row m)))))
(lout ""))
)
),
 
_start: (λ
(load-table tabl txt fieldSep: "$" :emptyEls)
 
(for i in Seq(0 (num-cols tabl)) do (= n 0)
(tsd-query tabl
reduce: [i]
as: [[String()]]
using: (λ (set n (max (size (get @row 0)) n))))
(append colWidths n)
)
(textout :right "") (print)
(lout :left "") (print)
(lout "") (print true)
)
}</syntaxhighlight>{{out}}
<pre>
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program a line
that aligns each column of fields by ensuring that words in each
column are separated by at least one space. that words in each
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. be either left
 
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program a line
that aligns each column of fields by ensuring that words in each
column are separated by at least one space. that words in each
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. be either left
 
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program a line
that aligns each column of fields by ensuring that words in each
column are separated by at least one space. that words in each
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. be either left
</pre>
 
=={{header|TSE SAL}}==
<syntaxhighlight lang="tsesal">
INTEGER PROC FNBlockChangeColumnAlignLeftB( INTEGER columnTotalI, INTEGER spaceTotalI, INTEGER buffer1I )
INTEGER B = FALSE
INTEGER downB = TRUE
INTEGER minI = 1
INTEGER I = 0
INTEGER J = 0
INTEGER K = 0
INTEGER L = 0
INTEGER buffer2I = 0
STRING s[255] = ""
INTEGER wordRightB = FALSE
STRING s1[255] = Query( WordSet )
IF ( NOT ( IsBlockInCurrFile() ) ) Warn( "Please mark a block" ) B = FALSE RETURN( B ) ENDIF // return from the current procedure if no block is marked
Set( BREAK, ON )
PushPosition()
PushBlock()
Set( WordSet, ChrSet( "a-zA-Z0-9_,." ) )
PushPosition()
buffer2I = CreateTempBuffer()
PopPosition()
PushPosition()
PushBlock()
DO 100 TIMES
AddLine( "", buffer2I )
ENDDO
PopBlock()
PopPosition()
GotoBlockBegin()
I = minI - 1
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
IF NOT LFind( "^$", "cgx" )
BegLine()
REPEAT
s = GetWord()
IF NOT ( s == "" )
s = Trim( s )
I = I + 1
IF ( I > columnTotalI )
I = minI
ENDIF
J = Length( s )
PushPosition()
PushBlock()
GotoBufferId( buffer2I )
GotoLine( I )
//
IF ( CurrLineLen() == 0 )
BegLine()
InsertText( Format( Str( J ), " " ), _INSERT_ )
ELSE
K = Val( Trim( GetText( 1, MAXSTRINGLEN ) ) )
IF ( J > K )
BegLine()
DelToEol()
BegLine()
InsertText( Str( J ), _INSERT_ )
ENDIF
ENDIF
PopBlock()
PopPosition()
wordRightB = WordRight()
ENDIF
UNTIL ( s == "" ) OR ( NOT wordRightB )
ENDIF
downB = Down()
ENDWHILE
GotoBlockBegin()
I = minI - 1
L = 1
K = 1
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
IF NOT LFind( "^$", "cgx" )
BegLine()
REPEAT
B = FALSE
s = GetWord()
IF NOT ( s == "" )
s = Trim( s )
I = I + 1
IF ( I > columnTotalI )
I = minI
K = 1
L = L + 1
ENDIF
//
PushPosition()
PushBlock()
GotoBufferId( buffer2I )
GotoLine( I )
J = Val( Trim( GetText( 1, MAXSTRINGLEN ) ) )
PopPosition()
PopBlock()
PushPosition()
PushBlock()
GotoBufferId( buffer1I )
GotoLine( L )
GotoColumn( K )
InsertText( s, _INSERT_ )
K = K + J + spaceTotalI
PopBlock()
PopPosition()
wordRightB = WordRight()
ENDIF
UNTIL ( s == "" ) OR ( NOT wordRightB )
ENDIF
AddLine( "", buffer1I )
downB = Down()
ENDWHILE
OneWindow()
VWindow()
GotoWindow( 1 )
GotoBufferId( buffer2I )
GotoWindow( 2 )
GotoBufferId( buffer1I )
B = TRUE
Set( WordSet, s1 )
PopPosition()
PopBlock()
RETURN( B )
END
//
PROC Main()
STRING s1[255] = "12" // change this
STRING s2[255] = "2" // change this
INTEGER bufferI = 0
PushPosition()
bufferI = CreateTempBuffer()
PopPosition()
IF ( NOT ( Ask( "block: change: column: align: left: columnTotalI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
IF ( NOT ( Ask( "block: change: column: align: left: spaceTotalI = ", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF
Message( FNBlockChangeColumnAlignLeftB( Val( s1 ), Val( s2 ), bufferI ) ) // gives e.g. TRUE
GotoBufferId( bufferI )
END
</syntaxhighlight>
{{out}} <pre>
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.
</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
MODE DATA
Line 8,573 ⟶ 10,079:
ENDLOOP
SET exampletext=JOIN(new1,"$",new2,new3,new4,new5,new6,new7,new8,new9,new10,new11,new12)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,587 ⟶ 10,093:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txr">@(collect)
@ (coll)@{item /[^$]+/}@(end)
@(end)
Line 8,613 ⟶ 10,119:
@{pi @(- [cw i] (trunc (- [cw i] (length pi)) 2))} @(end)
@ (end)
@(end)</langsyntaxhighlight>
 
<pre>$ txr align-columns.txr align-columns.dat
Line 8,637 ⟶ 10,143:
=={{header|UNIX Shell}}==
This is a draft implementation of the "align columns" problem using Unix shell commands. The key tool for left and right justified text is the "rs" command. Centered text is a little more complex, since this is not a feature currently in "rs" (''The centered solution will be added later.'')
<langsyntaxhighlight lang="bash">
cat <<EOF_OUTER > just-nocenter.sh
#!/bin/sh
Line 8,675 ⟶ 10,181:
exit
EOF_OUTER
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="sh">
<lang sh>
$ ./just-nocenter.sh
Given a text file of many lines, where fields within a line
Line 8,692 ⟶ 10,198:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
</lang>
 
The centered output will be added later, when I've more time. '' I did this in about 10 minutes.''
Line 8,699 ⟶ 10,205:
Note that the left-justified case can be handled trivially by the <tt>column</tt> command, which ships with modern Linux and macOS systems:
 
<langsyntaxhighlight lang="sh">tr '$' ' ' | column -t</langsyntaxhighlight>
 
{{Out}}
Line 8,716 ⟶ 10,222:
For right justification, each word's string of trailing blanks is moved to the beginning,
and for center justification, the trailing blanks are divided equally between the beginning and end of each word.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
text =
Line 8,735 ⟶ 10,241:
#show+
 
main = mat0 <.just_left,just_center,just_right> text</langsyntaxhighlight>
{{out}}
<pre style="height:17ex;overflow:scroll">
Line 8,764 ⟶ 10,270:
Both arguments are optional and default to "left" and 1 respectively.
 
<syntaxhighlight lang="vb">
<lang vb>
Public Sub TestSplit(Optional align As String = "left", Optional spacing As Integer = 1)
Dim word() As String
Line 8,830 ⟶ 10,336:
Next l
End Sub
</syntaxhighlight>
</lang>
 
{{out}}
Line 8,854 ⟶ 10,360:
=={{header|VBScript}}==
{{trans|Rexx}}
<langsyntaxhighlight lang="vb">' Align columns - RC - VBScript
Const nr=16, nc=16
ReDim d(nc),t(nr), wor(nr,nc)
Line 8,916 ⟶ 10,422:
xRTrim = cc
End Function 'xRTrim
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,946 ⟶ 10,452:
=={{header|Vedit macro language}}==
This implementation converts the file currently being edited. The file can then be saved with different filename if required.
<langsyntaxhighlight lang="vedit">RS(10, "$") // Field separator
#11 = 1 // Align: 1 = left, 2 = center, 3 = right
 
Line 8,985 ⟶ 10,491:
}
Line(1, ERRBREAK)
}</langsyntaxhighlight>
 
{{out}}
Line 9,013 ⟶ 10,519:
 
=={{header|Visual Basic}}==
<langsyntaxhighlight lang="vb">Sub AlignCols(Lines, Optional Align As AlignmentConstants, Optional Sep$ = "$", Optional Sp% = 1)
Dim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0)
Line 9,028 ⟶ 10,534:
Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), "", vbLf);
Next i, j
End Sub</langsyntaxhighlight>
Usage:<langsyntaxhighlight lang="vb">Sub Main() 'usage of the above
Const Text$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & vbLf & _
"are$delineated$by$a$single$'dollar'$character,$write$a$program" & vbLf & _
Line 9,040 ⟶ 10,546:
Debug.Print vbLf; "-- Center:": AlignCols Split(Text, vbLf), vbCenter
Debug.Print vbLf; "-- Right:": AlignCols Split(Text, vbLf), vbRightJustify
End Sub</langsyntaxhighlight>
{{out}}
<pre>-- Left:
Line 9,067 ⟶ 10,573:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vb">Module Module1
Private Delegate Function Justification(s As String, width As Integer) As String
 
Line 9,131 ⟶ 10,637:
End Sub
 
End Module</langsyntaxhighlight>
 
{{out}}
Line 9,157 ⟶ 10,663:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
 
=={{header|V (Vlang)}}==
Currently (5/2022) V (Vlang) uses string interpolation so `$` have to be escaped. Variables in formatting aren't currently allowed, and if they were only right/left are currently valid options
<syntaxhighlight lang="v (vlang)">
const text = "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."
struct Formatter {
mut:
text [][]string
width []int
}
fn new_formatter(text string) Formatter {
mut f := Formatter{}
for line in text.split_into_lines() {
mut words := line.split("\$")
for words[words.len-1] == "" {
words = words[..words.len-1]
}
f.text << words
for i, word in words {
if i == f.width.len {
f.width << word.len
} else if word.len > f.width[i] {
f.width[i] = word.len
}
}
}
return f
}
enum Justify {
left = 0
middle
right
}
fn (f Formatter) print(j Justify) {
for line in f.text {
for i, word in line {
match j {
.left {
print('$word${' '.repeat(f.width[i]-word.len)} ')
}
.middle {
mut extra := 0
if (f.width[i]%2==1 && word.len%2==0) || (f.width[i]%2==0 && word.len%2==1) {
extra++
}
print('${' '.repeat((f.width[i]-word.len)/2)}$word${' '.repeat((f.width[i]-word.len)/2+extra)} ')
}
.right {
print('${' '.repeat(f.width[i]-word.len)}$word ')
}
}
}
println("")
}
println("")
}
fn main() {
f := new_formatter(text)
f.print(Justify.left)
f.print(Justify.middle)
f.print(Justify.right)
}</syntaxhighlight>
 
{{out}}
<pre>
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.
 
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.
 
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.
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
import "./fmt" for Fmt
 
var LEFT = 0
Line 9,213 ⟶ 10,815:
var fileName = "align_cols.txt"
var lines = getLines.call(fileName)
for (i in 0..2) alignCols.call(lines, i)</langsyntaxhighlight>
 
{{out}}
Line 9,241 ⟶ 10,843:
justified, right justified, or center justified within its column.
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">
 
string 0;
def LF=$0A, CR=$0D;
def Left, Right, Center;
 
proc AlignCols(S); \Display string S with its columns aligned
char S, C, Field(80), ColWidth(80);
int I, J, N, Just;
 
proc Justify;
int T;
 
proc SpOut(M); \Output M space characters
int M, K;
for K:= 0 to M-1 do ChOut(0, ^ );
 
proc FieldOut; \Output Field of N characters
int K;
for K:= 0 to N-1 do ChOut(0, Field(K));
 
[case Just of
Left: [FieldOut(N); SpOut(ColWidth(J)-N+1)];
Right: [SpOut(ColWidth(J)-N+1); FieldOut(N)];
Center:[T:= ColWidth(J)-N+1;
SpOut(T/2); FieldOut(N); SpOut(T/2 + rem(0))]
other [];
];
 
[\Get width (in characters) of each column
for J:= 0 to 80-1 do ColWidth(J):= 0;
I:= 0; J:= 0; N:= 0;
loop [repeat C:= S(I); I:= I+1 until C # CR;
if N > ColWidth(J) then ColWidth(J):= N;
case C of
0: quit;
^$: [N:= 0; J:= J+1];
LF: [N:= 0; J:= J+1; J:= 0]
other N:= N+1;
];
for Just:= Left to Center do
[I:= 0; J:= 0; N:= 0;
loop [repeat C:= S(I); I:= I+1 until C # CR;
case C of
0: [Justify(Just); CrLf(0); quit];
^$: [Justify(Just); N:= 0; J:= J+1];
LF: [Justify(Just); CrLf(0); N:= 0; J:= 0]
other [Field(N):= C; N:= N+1];
];
CrLf(0);
];
];
 
AlignCols("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.")
</syntaxhighlight>
{{out}}
<pre>
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.
 
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.
 
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.
</pre>
 
=={{header|Yabasic}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="yabasic">theString$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
theString$ = theString$ + "are$delineated$by$a$single$'dollar'$character,$write$a$program"
theString$ = theString$ + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
theString$ = theString$ + "column$are$separated$by$at$least$one$space."
theString$ = theString$ + "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
theString$ = theString$ + "justified,$right$justified,$or$center$justified$within$its$column."
x = shoTable(theString$, "left", 6)
x = shoTable(theString$, "right", 6)
x = shoTable(theString$, "center", 6)
end
 
sub word$(sr$, wn, delim$)
local i, j, n, sd, sl, sl2
local s$, res$, d$
d$ = delim$
j = wn
if j = 0 j = j+1
res$ = "" : s$ = sr$
if d$ = "" d$ = " "
sd = len(d$) : sl = len(s$)
do
n = instr(s$,d$)
j = j - 1
if j = 0 then
if n = 0 then res$ = s$ else res$ = mid$(s$, 1, n-1) : fi
return res$
fi
if n = 0 return res$
if n = sl-sd then res$ = "" : return res$ : fi
sl2 = sl-n
s$ = mid$(s$, n+1, sl2)
sl = sl2
loop
return res$
end sub
 
sub shoTable(theString$, align$, across)
local i, a$, b$
 
print "------------ align:", align$, " -- across:", across, " ------------"
dim siz(across)
b$ = " "
while word$(theString$, i+1, "$") <> ""
siz(mod(i, across)) = max(siz(mod(i, across)), len(word$(theString$, i+1, "$")))
i = i+1
wend
for i = 0 to across - 1
siz(i) = siz(i)+1
if siz(i) and 1 siz(i) = siz(i)+1
next i
i = 0
a$ = word$(theString$, i+1, "$")
while a$ <> ""
s = siz(mod(i, across)) - len(a$)
if align$ = "right" a$ = left$(b$, s) + a$
if align$ = "left" a$ = a$ + left$(b$, s)
if align$ = "center" a$ = left$(b$, int(s / 2)) + a$ + left$(b$, int(s / 2) + (s and 1))
print "|", a$;
i = i + 1
if mod(i, across) = 0 print "|"
a$ = word$(theString$, i+1, "$")
wend
print
end sub</syntaxhighlight>
{{out}}
<pre>Same as Run BASIC entry.</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn format(text,how){
words:=text.split("$").apply("split").flatten();
max:=words.reduce(fcn(p,n){ n=n.len(); n>p and n or p },0);
Line 9,258 ⟶ 11,017:
do{ w.pump(wordsPerCol,d,fmt).append("\n") } while(not w.atEnd);
d.text;
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">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"
Line 9,269 ⟶ 11,028:
format(text,-1).print();
format(text, 0).print();
format(text, 1).print();</langsyntaxhighlight>
Blow apart the text into a list of words, find max len of any word, calc how many words will fit on a 80 col line, format all words into a bit bucket line at a time. Formatting is "%-ms" or "%ms" for left & right justify (m is field width), calculated for center. fmt is the string format method or center calc function, depending. Where string formatting can be used, it would be better to format all words in a line in one go but the code would be longer.
{{out}}
Line 9,306 ⟶ 11,065:
=={{header|ZX Spectrum Basic}}==
The max width (without 'hack') of ZX Spectrum screen is 32 characters. The text sample is adapted for this feature.
<langsyntaxhighlight lang="zxbasic"> 5 BORDER 2
10 DATA 6
20 DATA "The$problem$of$Speccy$"
Line 9,352 ⟶ 11,111:
3090 NEXT i
3095 PRINT
3100 RETURN</langsyntaxhighlight>
 
{{out}}Left alignement example:
290

edits