Align columns: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 30: Line 30:
=={{header|11l}}==
=={{header|11l}}==
{{trans|D}}
{{trans|D}}
<lang 11l>V txt = ‘Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
<syntaxhighlight 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
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 53: Line 53:
print(justify(word, max_widths[L.index]), end' ‘ ’)
print(justify(word, max_widths[L.index]), end' ‘ ’)
print()
print()
print(‘- ’ * 52)</lang>
print(‘- ’ * 52)</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Align columns 12/04/2019
<syntaxhighlight lang=360asm>* Align columns 12/04/2019
ALICOL CSECT
ALICOL CSECT
USING ALICOL,R13 base register
USING ALICOL,R13 base register
Line 235: Line 235:
PG DS CL120
PG DS CL120
REGEQU
REGEQU
END ALICOL </lang>
END ALICOL </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 262: Line 262:


=={{header|8th}}==
=={{header|8th}}==
<lang Forth>
<syntaxhighlight lang=Forth>
quote | Given$a$text$file$of$many$lines,$where$fields$within$a$line$
quote | Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 308: Line 308:
bye ;
bye ;


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 337: Line 337:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<lang AArch64 Assembly>
<syntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program alignColumn64.s */
/* program alignColumn64.s */
Line 666: Line 666:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
LEFT :
LEFT :
Line 693: Line 693:
</pre>
</pre>
=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>report z_align no standard page header.
<syntaxhighlight lang=ABAP>report z_align no standard page header.
start-of-selection.
start-of-selection.


Line 769: Line 769:
sy-linno = sy-linno - 1.
sy-linno = sy-linno - 1.
endloop.
endloop.
endform.</lang>
endform.</syntaxhighlight>


<pre style="height:15ex;overflow:scroll">Given a text file of many lines, where fields within a line
<pre style="height:15ex;overflow:scroll">Given a text file of many lines, where fields within a line
Line 794: Line 794:
=={{header|Action!}}==
=={{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.
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.
<lang Action!>DEFINE LINES_COUNT="10"
<syntaxhighlight lang=Action!>DEFINE LINES_COUNT="10"
DEFINE COLUMNS_COUNT="20"
DEFINE COLUMNS_COUNT="20"
DEFINE WORDS_COUNT="100"
DEFINE WORDS_COUNT="100"
Line 1,002: Line 1,002:
OD
OD


RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Align_columns.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Align_columns.png Screenshot from Atari 8-bit computer]
Line 1,032: Line 1,032:
=={{header|Ada}}==
=={{header|Ada}}==
{{libheader|Simple components for Ada}}
{{libheader|Simple components for Ada}}
<lang ada>with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
<syntaxhighlight lang=ada>with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Strings_Edit; use Strings_Edit;
with Strings_Edit; use Strings_Edit;
Line 1,096: Line 1,096:
end loop;
end loop;
Close (File);
Close (File);
end Column_Aligner;</lang>
end Column_Aligner;</syntaxhighlight>
Formatted file sample:
Formatted file sample:
<pre style="height:15ex;overflow:scroll">
<pre style="height:15ex;overflow:scroll">
Line 1,120: Line 1,120:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>data b;
<syntaxhighlight lang=aime>data b;
file f;
file f;
text n, t;
text n, t;
Line 1,164: Line 1,164:
}
}
o_newline();
o_newline();
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>left justified
<pre>left justified
Line 1,191: Line 1,191:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>STRING nl = REPR 10;
<syntaxhighlight lang=algol68>STRING nl = REPR 10;
STRING text in list := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"+nl+
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+
"are$delineated$by$a$single$'dollar'$character,$write$a$program"+nl+
Line 1,256: Line 1,256:
aligner(page, align OF aligners[index])
aligner(page, align OF aligners[index])
OD
OD
END</lang>
END</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<lang Amazing Hopper>
<syntaxhighlight lang=Amazing Hopper>
#define IGet(__N__,__X__) [__N__]SGet(__X__)
#define IGet(__N__,__X__) [__N__]SGet(__X__)


Line 1,310: Line 1,310:
Print("Left Pad:\n", display Left, Newl, "Right Pad:\n", display Right, Newl, "Center Pad:\n", display Center,Newl)
Print("Left Pad:\n", display Left, Newl, "Right Pad:\n", display Right, Newl, "Center Pad:\n", display Center,Newl)
End
End
</syntaxhighlight>
</lang>
{{out}}
{{out}}
Sample String was saved into "sample.txt" file.
Sample String was saved into "sample.txt" file.
Line 1,346: Line 1,346:


{{trans|JavaScript}}
{{trans|JavaScript}}
<lang AppleScript>-- COLUMN ALIGNMENTS ---------------------------------------------------------
<syntaxhighlight lang=AppleScript>-- COLUMN ALIGNMENTS ---------------------------------------------------------


property pstrLines : ¬
property pstrLines : ¬
Line 1,597: Line 1,597:
return lst
return lst
end tell
end tell
end zipWith</lang>
end zipWith</syntaxhighlight>
{{Out}}
{{Out}}
<pre> Given a text file of many lines, where fields within a line
<pre> Given a text file of many lines, where fields within a line
Line 1,621: Line 1,621:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program alignColumn.s */
/* program alignColumn.s */
Line 1,947: Line 1,947:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
LEFT :
LEFT :
Line 1,974: Line 1,974:
</pre>
</pre>
=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>text: {
<syntaxhighlight lang=rebol>text: {
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 1,988: Line 1,988:
loop line 'word -> prints pad word 12
loop line 'word -> prints pad word 12
print ""
print ""
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,001: Line 2,001:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==


<lang AutoHotkey>Alignment := "L" ; Options: L, R, C
<syntaxhighlight lang=AutoHotkey>Alignment := "L" ; Options: L, R, C
Text =
Text =
( LTrim
( LTrim
Line 2,049: Line 2,049:
Return Ret
Return Ret
}
}
</syntaxhighlight>
</lang>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>
<syntaxhighlight lang=AutoIt>
; == If the given text is in an file, it will read with:
; == If the given text is in an file, it will read with:
#include <File.au3>
#include <File.au3>
Line 2,136: Line 2,136:
EndSwitch
EndSwitch
EndFunc ;==>_GetAligned
EndFunc ;==>_GetAligned
</syntaxhighlight>
</lang>
Example output in Alignment: left - center - right - left - center - right - left - center - right - left - center - right
Example output in Alignment: left - center - right - left - center - right - left - center - right - left - center - right
<pre>
<pre>
Line 2,148: Line 2,148:


=={{header|AWK}}==
=={{header|AWK}}==
<lang AWK>
<syntaxhighlight lang=AWK>
# syntax: GAWK -f ALIGN_COLUMNS.AWK ALIGN_COLUMNS.TXT
# syntax: GAWK -f ALIGN_COLUMNS.AWK ALIGN_COLUMNS.TXT
BEGIN {
BEGIN {
Line 2,190: Line 2,190:
}
}
function max(x,y) { return((x > y) ? x : y) }
function max(x,y) { return((x > y) ? x : y) }
</syntaxhighlight>
</lang>
<p>Output:</p>
<p>Output:</p>
<pre>
<pre>
Line 2,227: Line 2,227:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang freebasic>
<syntaxhighlight lang=freebasic>
DECLARE in$[] = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", \
DECLARE in$[] = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", \
"are$delineated$by$a$single$'dollar'$character,$write$a$program", \
"are$delineated$by$a$single$'dollar'$character,$write$a$program", \
Line 2,262: Line 2,262:
Print_In_Columns(1)
Print_In_Columns(1)
Print_In_Columns(2)
Print_In_Columns(2)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,292: Line 2,292:
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DATA 6
<syntaxhighlight lang=bbcbasic> DATA 6
DATA "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
DATA "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
DATA "are$delineated$by$a$single$'dollar'$character,$write$a$program"
DATA "are$delineated$by$a$single$'dollar'$character,$write$a$program"
Line 2,347: Line 2,347:
WHEN "right": = STRING$(field%-LEN(word$), " ") + word$
WHEN "right": = STRING$(field%-LEN(word$), " ") + word$
ENDCASE
ENDCASE
= word$</lang>
= word$</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang basic>10 rem ********************************
<syntaxhighlight lang=basic>10 rem ********************************
20 rem print words in columns
20 rem print words in columns
30 rem commodore basic 2.0
30 rem commodore basic 2.0
Line 2,415: Line 2,415:
640 data "column$are$separated$by$at$least$one$space."
640 data "column$are$separated$by$at$least$one$space."
650 data "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
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"</lang>
660 data "justified,$right$justified,$or$center$justified$within$its$column"</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang=dos>@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
mode con cols=103
mode con cols=103
Line 2,501: Line 2,501:
)
)
endlocal & set %~2=%len%
endlocal & set %~2=%len%
exit /b</lang>
exit /b</syntaxhighlight>
{{out}}
{{out}}
<pre>Given a text file of many lines where fields within a line
<pre>Given a text file of many lines where fields within a line
Line 2,525: Line 2,525:


=={{header|Beads}}==
=={{header|Beads}}==
<lang beads>beads 1 program 'Align columns'
<syntaxhighlight lang=beads>beads 1 program 'Align columns'
const
const
Line 2,577: Line 2,577:
log "\n{v} justified\n"
log "\n{v} justified\n"
div_line
div_line
show_table(v)</lang>
show_table(v)</syntaxhighlight>


{{out}}
{{out}}
Line 2,629: Line 2,629:
=={{header|BQN}}==
=={{header|BQN}}==
A function which returns a rectangular 2D array which represents the lines.
A function which returns a rectangular 2D array which represents the lines.
<lang bqn>Split ← (⊢-˜+`׬)∘=⊔⊢
<syntaxhighlight lang=bqn>Split ← (⊢-˜+`׬)∘=⊔⊢
PadRow ← {
PadRow ← {
w‿t𝕊𝕩: # t → type.
w‿t𝕊𝕩: # t → type.
Line 2,640: Line 2,640:
Align ← {{𝕨∾' '∾𝕩}´˘⍉" "‿𝕨⊸PadRow˘⍉>⟨""⟩‿0 PadRow '$' Split¨(@+10) Split 𝕩}
Align ← {{𝕨∾' '∾𝕩}´˘⍉" "‿𝕨⊸PadRow˘⍉>⟨""⟩‿0 PadRow '$' Split¨(@+10) Split 𝕩}


1 Align text</lang>
1 Align text</syntaxhighlight>
<lang bqn>┌─
<syntaxhighlight lang=bqn>┌─
╵" Given a text file of many lines, where fields within a line
╵" Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
are delineated by a single 'dollar' character, write a program
Line 2,648: Line 2,648:
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. "
justified, right justified, or center justified within its column. "
┘</lang>
┘</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=dGV4dOKGkCJHaXZlbiRhJHRleHQkZmlsZSRvZiRtYW55JGxpbmVzLCR3aGVyZSRmaWVsZHMkd2l0aGluJGEkbGluZSQKYXJlJGRlbGluZWF0ZWQkYnkkYSRzaW5nbGUkJ2RvbGxhcickY2hhcmFjdGVyLCR3cml0ZSRhJHByb2dyYW0KdGhhdCRhbGlnbnMkZWFjaCRjb2x1bW4kb2YkZmllbGRzJGJ5JGVuc3VyaW5nJHRoYXQkd29yZHMkaW4kZWFjaCQKY29sdW1uJGFyZSRzZXBhcmF0ZWQkYnkkYXQkbGVhc3Qkb25lJHNwYWNlLgpGdXJ0aGVyLCRhbGxvdyRmb3IkZWFjaCR3b3JkJGluJGEkY29sdW1uJHRvJGJlJGVpdGhlciRsZWZ0JApqdXN0aWZpZWQsJHJpZ2h0JGp1c3RpZmllZCwkb3IkY2VudGVyJGp1c3RpZmllZCR3aXRoaW4kaXRzJGNvbHVtbi4iCgpTcGxpdCDihpAgKOKKoi3LnCtgw5fCrCniiJg94oqU4oqiClBhZFJvdyDihpAgewogIHfigL908J2VivCdlak6ICMgdCDihpIgdHlwZS4KICAgICAgICAjIDAg4oaSIGxlZnQKICAgICAgICAjIDEg4oaSIHJpZ2h0CiAgICAgICAgIyAyIOKGkiBjZW50ZXIKIHBzdHlsZeKGkHTiipHin6h7MOKAv/Cdlal9LHvwnZWp4oC/MH0se+KfqOKMivCdlanDtzIs4oyI8J2VqcO3MuKfqX3in6kKIPCdlal7KOKKo+KIvvCdlajiiL7iiqIpwrQoUHN0eWxlIPCdlakpL8KoPHd9wqgo4oyIwrQt4oqiKeKJoMKo8J2VqQp9CkFsaWduIOKGkCB7e/CdlajiiL4nICfiiL7wnZWpfcK0y5jijYkiICLigL/wnZWo4oq4UGFkUm93y5jijYk+4p+oIiLin6nigL8wIFBhZFJvdyAnJCcgU3BsaXTCqChAKzEwKSBTcGxpdCDwnZWpfQoKMSBBbGlnbiB0ZXh0CgoK Try It!]
[https://mlochbaum.github.io/BQN/try.html#code=dGV4dOKGkCJHaXZlbiRhJHRleHQkZmlsZSRvZiRtYW55JGxpbmVzLCR3aGVyZSRmaWVsZHMkd2l0aGluJGEkbGluZSQKYXJlJGRlbGluZWF0ZWQkYnkkYSRzaW5nbGUkJ2RvbGxhcickY2hhcmFjdGVyLCR3cml0ZSRhJHByb2dyYW0KdGhhdCRhbGlnbnMkZWFjaCRjb2x1bW4kb2YkZmllbGRzJGJ5JGVuc3VyaW5nJHRoYXQkd29yZHMkaW4kZWFjaCQKY29sdW1uJGFyZSRzZXBhcmF0ZWQkYnkkYXQkbGVhc3Qkb25lJHNwYWNlLgpGdXJ0aGVyLCRhbGxvdyRmb3IkZWFjaCR3b3JkJGluJGEkY29sdW1uJHRvJGJlJGVpdGhlciRsZWZ0JApqdXN0aWZpZWQsJHJpZ2h0JGp1c3RpZmllZCwkb3IkY2VudGVyJGp1c3RpZmllZCR3aXRoaW4kaXRzJGNvbHVtbi4iCgpTcGxpdCDihpAgKOKKoi3LnCtgw5fCrCniiJg94oqU4oqiClBhZFJvdyDihpAgewogIHfigL908J2VivCdlak6ICMgdCDihpIgdHlwZS4KICAgICAgICAjIDAg4oaSIGxlZnQKICAgICAgICAjIDEg4oaSIHJpZ2h0CiAgICAgICAgIyAyIOKGkiBjZW50ZXIKIHBzdHlsZeKGkHTiipHin6h7MOKAv/Cdlal9LHvwnZWp4oC/MH0se+KfqOKMivCdlanDtzIs4oyI8J2VqcO3MuKfqX3in6kKIPCdlal7KOKKo+KIvvCdlajiiL7iiqIpwrQoUHN0eWxlIPCdlakpL8KoPHd9wqgo4oyIwrQt4oqiKeKJoMKo8J2VqQp9CkFsaWduIOKGkCB7e/CdlajiiL4nICfiiL7wnZWpfcK0y5jijYkiICLigL/wnZWo4oq4UGFkUm93y5jijYk+4p+oIiLin6nigL8wIFBhZFJvdyAnJCcgU3BsaXTCqChAKzEwKSBTcGxpdCDwnZWpfQoKMSBBbGlnbiB0ZXh0CgoK Try It!]


Line 2,660: Line 2,660:
{{works with|C sharp|C#|2+}}
{{works with|C sharp|C#|2+}}


<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
class ColumnAlignerProgram
class ColumnAlignerProgram
{
{
Line 2,733: Line 2,733:
}
}
}
}
}</lang>
}</syntaxhighlight>


===Newer version===
===Newer version===
Line 2,739: Line 2,739:


{{works with|C sharp|C#|8+}}
{{works with|C sharp|C#|8+}}
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.Linq;
using System.Linq;


Line 2,790: Line 2,790:
}
}


}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 2,821: Line 2,821:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>
<syntaxhighlight lang=Clojure>
(ns rosettacode.align-columns
(ns rosettacode.align-columns
(:require [clojure.contrib.string :as str]))
(:require [clojure.contrib.string :as str]))
Line 2,863: Line 2,863:


(print-table (aligned-table table :center))
(print-table (aligned-table table :center))
</syntaxhighlight>
</lang>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol>
<syntaxhighlight lang=cobol>
identification division.
identification division.
program-id. AlignColumns.
program-id. AlignColumns.
Line 2,950: Line 2,950:
end-perform
end-perform
.
.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang>
<lang>
Line 2,974: Line 2,974:
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
justified, right justified, or center justified within its column.
</syntaxhighlight>
</lang>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang=coffeescript>
pad = (n) ->
pad = (n) ->
s = ''
s = ''
Line 3,026: Line 3,026:
console.log "\n----- #{alignment}"
console.log "\n----- #{alignment}"
align input, alignment
align input, alignment
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang>
<lang>
Line 3,054: Line 3,054:
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
justified, right justified, or center justified within its column.
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun nonempty (seq)
<syntaxhighlight lang=lisp>(defun nonempty (seq)
(position-if (lambda (x) (declare (ignore x)) t) seq))
(position-if (lambda (x) (declare (ignore x)) t) seq))


Line 3,104: Line 3,104:
(format s "~~~d~a<~~a~~>" (1+ w) fmtmod))
(format s "~~~d~a<~~a~~>" (1+ w) fmtmod))
(princ "~}~%~}" s))
(princ "~}~%~}" s))
fields))</lang>
fields))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang=d>void main() {
import std.stdio, std.string, std.algorithm, std.range, std.typetuple;
import std.stdio, std.string, std.algorithm, std.range, std.typetuple;


Line 3,128: Line 3,128:
writefln("%-(%s %)", line.length.iota
writefln("%-(%s %)", line.length.iota
.map!(i => just(line[i], maxWidths[i], ' ')));
.map!(i => just(line[i], maxWidths[i], ' ')));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Given a txt file of many lines, where fields within a line
<pre>Given a txt file of many lines, where fields within a line
Line 3,151: Line 3,151:
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader|Delphi StdCtrls, Classes, SysUtils, StrUtils, Contnrs}}
{{libheader|Delphi StdCtrls, Classes, SysUtils, StrUtils, Contnrs}}
<lang Delphi>
<syntaxhighlight lang=Delphi>
USES
USES
StdCtrls, Classes, SysUtils, StrUtils, Contnrs;
StdCtrls, Classes, SysUtils, StrUtils, Contnrs;
Line 3,208: Line 3,208:
END;
END;
end;
end;
</syntaxhighlight>
</lang>


=={{header|E}}==
=={{header|E}}==


<lang e>pragma.enable("accumulator")
<syntaxhighlight lang=e>pragma.enable("accumulator")


def left(width, word) {
def left(width, word) {
Line 3,240: Line 3,240:
} + "\n"
} + "\n"
}
}
}</lang>
}</syntaxhighlight>


<lang e>? def text := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
<syntaxhighlight 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
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 3,271: Line 3,271:
column are separated by at least one space.
column are separated by at least one space.
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</lang>
justified, right justified, or center justified within its column.</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
Line 3,278: Line 3,278:
The String module of Elixir doesn't have the function of the center position adjusting.
The String module of Elixir doesn't have the function of the center position adjusting.
It calls and processes the function of 'Erlang'.
It calls and processes the function of 'Erlang'.
<lang elixir>defmodule Align do
<syntaxhighlight lang=elixir>defmodule Align do
def columns(text, alignment) do
def columns(text, alignment) do
fieldsbyrow = String.split(text, "\n", trim: true)
fieldsbyrow = String.split(text, "\n", trim: true)
Line 3,312: Line 3,312:
IO.puts "\n# #{alignment} Column-aligned output:"
IO.puts "\n# #{alignment} Column-aligned output:"
Align.columns(text, alignment)
Align.columns(text, alignment)
end)</lang>
end)</syntaxhighlight>


{{out}}
{{out}}
Line 3,342: Line 3,342:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>
<syntaxhighlight lang=erlang>
-module (align_columns).
-module (align_columns).
Line 3,380: Line 3,380:
Zipped = lists:zip (All_words, Words_length),
Zipped = lists:zip (All_words, Words_length),
[ apply(string, Alignment, [Word, Length + 1, $\s])
[ apply(string, Alignment, [Word, Length + 1, $\s])
|| {Word, Length} <- Zipped]. </lang>
|| {Word, Length} <- Zipped]. </syntaxhighlight>


{{out}}
{{out}}
Line 3,413: Line 3,413:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>constant data = {
<syntaxhighlight lang=euphoria>constant data = {
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
Line 3,473: Line 3,473:
end for
end for
puts(1,'\n')
puts(1,'\n')
end for</lang>
end for</syntaxhighlight>


{{out}}
{{out}}
Line 3,500: Line 3,500:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang=fsharp>open System
open System.IO
open System.IO


Line 3,532: Line 3,532:
format table align
format table align
printfn "%s" (new String('-', (Array.sum width) + width.Length - 1))
printfn "%s" (new String('-', (Array.sum width) + width.Length - 1))
0</lang>
0</syntaxhighlight>
Output, when called with a file containing the sample input
Output, when called with a file containing the sample input
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 3,557: Line 3,557:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: fry io kernel math math.functions math.order sequences
<syntaxhighlight lang=factor>USING: fry io kernel math math.functions math.order sequences
splitting strings ;
splitting strings ;
IN: rosetta.column-aligner
IN: rosetta.column-aligner
Line 3,596: Line 3,596:
: print-aligned ( text alignment -- )
: print-aligned ( text alignment -- )
[ split-and-pad flip ] dip align-columns flip
[ split-and-pad flip ] dip align-columns flip
[ [ write " " write ] each nl ] each ;</lang>
[ [ write " " write ] each nl ] each ;</syntaxhighlight>


example-text { +left+ +middle+ +right+ } [ print-aligned ] with each
example-text { +left+ +middle+ +right+ } [ print-aligned ] with each
Line 3,602: Line 3,602:
=={{header|FBSL}}==
=={{header|FBSL}}==
Using a multiline string:
Using a multiline string:
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang=qbasic>#APPTYPE CONSOLE


DIM s = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
DIM s = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 3,636: Line 3,636:
NEXT
NEXT


PAUSE</lang>
PAUSE</syntaxhighlight>
{{out}}
{{out}}
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 3,649: Line 3,649:
=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>\ align columns
<syntaxhighlight lang=forth>\ align columns


: split ( addr len char -- addr len1 addr len-len1 )
: split ( addr len char -- addr len1 addr len-len1 )
Line 3,718: Line 3,718:
\ cleanup
\ cleanup
nip free throw
nip free throw
column-widths free throw</lang>
column-widths free throw</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 3,736: Line 3,736:


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.
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.
<lang Fortran>
<syntaxhighlight lang=Fortran>
SUBROUTINE RAKE(IN,M,X,WAY) !Casts forth text in fixed-width columns.
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.
Collates column widths so that each column is wide enough for its widest member.
Line 3,831: Line 3,831:
CALL RAKE(IN,M,"$",+1) !Align right.
CALL RAKE(IN,M,"$",+1) !Align right.
END !That's all.
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:
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>
<pre>
Line 3,865: Line 3,865:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64


Sub Split(s As String, sep As String, result() As String)
Sub Split(s As String, sep As String, result() As String)
Line 3,962: Line 3,962:
Next i
Next i


Close #1 : Close #2 : Close #3</lang>
Close #1 : Close #2 : Close #3</syntaxhighlight>


{{out}}
{{out}}
Line 4,005: Line 4,005:
=={{header|FutureBasic}}==
=={{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.
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.
<lang futurebasic>
<syntaxhighlight lang=futurebasic>
include "NSLog.incl"
include "NSLog.incl"


Line 4,052: Line 4,052:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 4,081: Line 4,081:
=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=023b4c5144d45e047abe02ebf5c4525a Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=023b4c5144d45e047abe02ebf5c4525a Click this link to run this code]'''
<lang gambas>Public Sub Main() 'Written in Gambas 3.9.2 as a Command line Application - 15/03/2017
<syntaxhighlight 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 siCount, siCounter, siLength As Short 'Counters
Dim siLongest As Short = -1 'To store the longest 'Word'
Dim siLongest As Short = -1 'To store the longest 'Word'
Line 4,124: Line 4,124:
Next
Next


End</lang>
End</syntaxhighlight>


{{out}}
{{out}}
Line 4,151: Line 4,151:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 4,211: Line 4,211:
f.print(middle)
f.print(middle)
f.print(right)
f.print(right)
}</lang>
}</syntaxhighlight>
<pre>
<pre>
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 4,237: Line 4,237:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def alignColumns = { align, rawText ->
<syntaxhighlight lang=groovy>def alignColumns = { align, rawText ->
def lines = rawText.tokenize('\n')
def lines = rawText.tokenize('\n')
def words = lines.collect { it.tokenize(/\$/) }
def words = lines.collect { it.tokenize(/\$/) }
Line 4,250: Line 4,250:


words.each { padAll(justify[align], columnWidths, it).each { print it }; println() }
words.each { padAll(justify[align], columnWidths, it).each { print it }; println() }
}</lang>
}</syntaxhighlight>


Test Program:
Test Program:
<lang groovy>def rawTextInput = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
<syntaxhighlight 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
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 4,264: Line 4,264:
alignColumns(align, rawTextInput)
alignColumns(align, rawTextInput)
println()
println()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,293: Line 4,293:
=={{header|Harbour}}==
=={{header|Harbour}}==


<lang visualfoxpro>
<syntaxhighlight lang=visualfoxpro>
PROCEDURE Main()
PROCEDURE Main()
LOCAL a := { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",;
LOCAL a := { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",;
Line 4,334: Line 4,334:
RETURN
RETURN
</syntaxhighlight>
</lang>
Output:
Output:
<lang text>----Left aligned columns----
<syntaxhighlight lang=text>----Left aligned columns----
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
are delineated by a single 'dollar' character, write a program
Line 4,358: Line 4,358:
column are separated by at least one space.
column are separated by at least one space.
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</lang>
justified, right justified, or center justified within its column.</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List (unfoldr, transpose)
<syntaxhighlight lang=haskell>import Data.List (unfoldr, transpose)
import Control.Arrow (second)
import Control.Arrow (second)


Line 4,386: Line 4,386:
where
where
dl = cw - length w
dl = cw - length w
(l, r) = (dl `div` 2, dl - l)</lang>
(l, r) = (dl `div` 2, dl - l)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,400: Line 4,400:
Or, using '''Text''' and its functions as an alternative to '''[Char]''' strings:
Or, using '''Text''' and its functions as an alternative to '''[Char]''' strings:


<lang haskell>import Prelude as P
<syntaxhighlight lang=haskell>import Prelude as P
import Data.Text as T
import Data.Text as T
(Text, pack, unpack, splitOn, unlines, unwords, length,
(Text, pack, unpack, splitOn, unlines, unwords, length,
Line 4,434: Line 4,434:
(zip cols ((T.length . maximumBy (comparing T.length)) <$> cols))
(zip cols ((T.length . maximumBy (comparing T.length)) <$> cols))
] <*>
] <*>
[justifyLeft, justifyRight, center]</lang>
[justifyLeft, justifyRight, center]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 4,459: Line 4,459:
=={{header|HicEst}}==
=={{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.
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.
<lang HicEst>
<syntaxhighlight lang=HicEst>
CHARACTER Fnam = "\HicEst\Rosetta\Align columns.txt"
CHARACTER Fnam = "\HicEst\Rosetta\Align columns.txt"


Line 4,486: Line 4,486:
WRITE() out
WRITE() out
ENDDO
ENDDO
END</lang>
END</syntaxhighlight>
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
are delineated by a single 'dollar' character, write a program
Line 4,509: Line 4,509:
An argument of <tt>left</tt>, <tt>center</tt>, or <tt>right</tt> controls the
An argument of <tt>left</tt>, <tt>center</tt>, or <tt>right</tt> controls the
column alignment. The default is left-alignment.
column alignment. The default is left-alignment.
<lang icon>global width
<syntaxhighlight lang=icon>global width


procedure main(args)
procedure main(args)
Line 4,538: Line 4,538:
write()
write()
}
}
end</lang>
end</syntaxhighlight>


Sample run:
Sample run:
Line 4,557: Line 4,557:


'''Solution'''
'''Solution'''
<lang j>'LEFT CENTER RIGHT'=: i.3 NB. justification constants
<syntaxhighlight lang=j>'LEFT CENTER RIGHT'=: i.3 NB. justification constants
NB.* alignCols v Format delimited text in justified columns
NB.* alignCols v Format delimited text in justified columns
Line 4,574: Line 4,574:
7 17 global oldbox NB. restore settings
7 17 global oldbox NB. restore settings
result
result
)</lang>
)</syntaxhighlight>


'''Example''':
'''Example''':
<lang j> text=: noun define
<syntaxhighlight lang=j> text=: noun define
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 4,600: Line 4,600:
column are separated by at least one space.
column are separated by at least one space.
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</lang>
justified, right justified, or center justified within its column.</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 4,607: Line 4,607:
{{libheader|Apache Commons Lang}}
{{libheader|Apache Commons Lang}}


<lang Java>import java.io.IOException;
<syntaxhighlight lang=Java>import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Files;
Line 4,750: Line 4,750:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 4,756: Line 4,756:
===Imperative===
===Imperative===


<lang JavaScript>
<syntaxhighlight lang=JavaScript>
var justification="center",
var justification="center",
input=["Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
input=["Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
Line 4,787: Line 4,787:
for(x=0;x<input.length;x++) input[x]=input[x].join(" ");
for(x=0;x<input.length;x++) input[x]=input[x].join(" ");
input=input.join("\n");
input=input.join("\n");
document.write(input);</lang>
document.write(input);</syntaxhighlight>


===Functional===
===Functional===


<lang JavaScript>//break up each string by '$'. The assumption is that the user wants the trailing $.
<syntaxhighlight lang=JavaScript>//break up each string by '$'. The assumption is that the user wants the trailing $.
var data = [
var data = [
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
Line 4,838: Line 4,838:


return zip(formattedCols).map(function (row) { return row.join(' '); }).join('\n');
return zip(formattedCols).map(function (row) { return row.join(' '); }).join('\n');
};</lang>
};</syntaxhighlight>




Line 4,844: Line 4,844:
Or (ES5) using transpose and zipWith:
Or (ES5) using transpose and zipWith:


<lang JavaScript>(function (strText) {
<syntaxhighlight lang=JavaScript>(function (strText) {
'use strict';
'use strict';
Line 4,976: Line 4,976:
Further,$allow$for$each$word$in$a$column$to$be$either$left$\n\
Further,$allow$for$each$word$in$a$column$to$be$either$left$\n\
justified,$right$justified,$or$center$justified$within$its$column."
justified,$right$justified,$or$center$justified$within$its$column."
);</lang>
);</syntaxhighlight>


{{Out}}
{{Out}}
Line 5,004: Line 5,004:
{{ Works with|jq|1.4}}
{{ 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.
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.
<lang jq># transpose a possibly jagged matrix
<syntaxhighlight lang=jq># transpose a possibly jagged matrix
def transpose:
def transpose:
if . == [] then []
if . == [] then []
Line 5,046: Line 5,046:
(""; . + ($line[$i]|justify($widths[$i])) ))
(""; . + ($line[$i]|justify($widths[$i])) ))
| join("\n")
| join("\n")
;</lang>
;</syntaxhighlight>
'''Example''':
'''Example''':
<lang jq>"Center:", format("center"), "",
<syntaxhighlight lang=jq>"Center:", format("center"), "",
"Left:", format("left"), "",
"Left:", format("left"), "",
"Right:", format("right")</lang>
"Right:", format("right")</syntaxhighlight>
{{Out}}
{{Out}}
<div style="overflow:scroll; height:200px;"><lang sh>$ jq -M -R -r -s -f Align_columns.jq Align_columns.txt
<div style="overflow:scroll; height:200px;"><syntaxhighlight lang=sh>$ jq -M -R -r -s -f Align_columns.jq Align_columns.txt
Center:
Center:
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 5,076: Line 5,076:
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
justified, right justified, or center justified within its column.
</lang></div>
</syntaxhighlight></div>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript ES5 entry.
From Javascript ES5 entry.
<lang javascript>/* Align columns, in Jsish */
<syntaxhighlight lang=javascript>/* Align columns, in Jsish */
function alignColumns(phrases:array, just:string) {
function alignColumns(phrases:array, just:string) {
var x, y, max, diff, left, right, cols=0;
var x, y, max, diff, left, right, cols=0;
Line 5,121: Line 5,121:
puts(alignColumns(trial, just), '\n');
puts(alignColumns(trial, just), '\n');
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,151: Line 5,151:
=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Python}}
{{trans|Python}}
<lang julia>txt = """Given\$a\$txt\$file\$of\$many\$lines,\$where\$fields\$within\$a\$line\$
<syntaxhighlight 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
are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program
that\$aligns\$each\$column\$of\$fields\$by\$ensuring\$that\$words\$in\$each\$
that\$aligns\$each\$column\$of\$fields\$by\$ensuring\$that\$words\$in\$each\$
Line 5,190: Line 5,190:
end
end
println("-"^sum(max_widths))
println("-"^sum(max_widths))
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,220: Line 5,220:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>import java.nio.charset.StandardCharsets
<syntaxhighlight lang=scala>import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.Paths
Line 5,282: Line 5,282:
else -> System.err.println("Error! Unknown alignment: " + alignment)
else -> System.err.println("Error! Unknown alignment: " + alignment)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Line 5,288: Line 5,288:
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.
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.


<lang scheme>
<syntaxhighlight lang=scheme>
{def txt
{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.}
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 5,327: Line 5,327:


{columns center txt} and {columns right txt} outputs can be seen in this website: http://lambdaway.free.fr/lambdawalks/?view=align_columns
{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}}==
=={{header|Lasso}}==
<lang Lasso>#!/usr/bin/lasso9
<syntaxhighlight lang=Lasso>#!/usr/bin/lasso9


local(text = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
local(text = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 5,396: Line 5,396:
}
}


prepcols(#text)</lang>
prepcols(#text)</syntaxhighlight>


{{out}}
{{out}}
Line 5,427: Line 5,427:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>mainwin 140 32
<syntaxhighlight lang=lb>mainwin 140 32


CRLF$ =chr$( 13)
CRLF$ =chr$( 13)
Line 5,504: Line 5,504:
end function
end function


end</lang>
end</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
{{works with|Lua|5.1}}
{{works with|Lua|5.1}}


<lang lua>
<syntaxhighlight lang=lua>
local tWord = {} -- word table
local tWord = {} -- word table
local tColLen = {} -- maximum word length in a column
local tColLen = {} -- maximum word length in a column
Line 5,570: Line 5,570:
return output
return output
end--alignColumn
end--alignColumn
</syntaxhighlight>
</lang>


Usage Example:
Usage Example:


<lang lua>
<syntaxhighlight lang=lua>
input =
input =
[[Given$a$text$file$of$many$lines,$where$fields$within$a$line$
[[Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 5,587: Line 5,587:
outputRight = alignColumn(input, "right")
outputRight = alignColumn(input, "right")
alignColumn(input, "center", "output.txt")
alignColumn(input, "center", "output.txt")
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module Align_Columns {
Module Align_Columns {
a$={Given$a$text$file$of$many$lines,$where$fields$within$a$line$
a$={Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 5,643: Line 5,643:
}
}
Align_Columns
Align_Columns
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,669: Line 5,669:
=={{header|Maple}}==
=={{header|Maple}}==
Assign the sample data.
Assign the sample data.
<lang Maple>
<syntaxhighlight lang=Maple>
txt :=
txt :=
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
Line 5,677: Line 5,677:
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"justified,$right$justified,$or$center$justified$within$its$column.\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.
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.
<lang Maple>
<syntaxhighlight lang=Maple>
AlignColumns := proc( txt, align :: { "left", "right", "centre" } := "centre" )
AlignColumns := proc( txt, align :: { "left", "right", "centre" } := "centre" )
uses StringTools;
uses StringTools;
Line 5,704: Line 5,704:
Join( J, "\n" )
Join( J, "\n" )
end proc:
end proc:
</syntaxhighlight>
</lang>
For the sample text, we get the following results.
For the sample text, we get the following results.
<lang Maple>
<syntaxhighlight lang=Maple>
> printf( "%s\n", AlignColumns( txt ) ):
> printf( "%s\n", AlignColumns( txt ) ):
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 5,735: Line 5,735:
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
justified, right justified, or center justified within its column.
</syntaxhighlight>
</lang>
Alternatively, this could be printed to a file (using fprintf instead of printf).
Alternatively, this could be printed to a file (using fprintf instead of printf).


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>TableForm[StringSplit[StringSplit[a,"\n"],"$"],TableAlignments -> Center]</lang>
<syntaxhighlight lang=Mathematica>TableForm[StringSplit[StringSplit[a,"\n"],"$"],TableAlignments -> Center]</syntaxhighlight>
Output with example text :
Output with example text :
[[File:centeredtext.png]]
[[File:centeredtext.png]]
Line 5,745: Line 5,745:
=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
center-justified formatting is not implemented here
center-justified formatting is not implemented here
<lang Matlab>
<syntaxhighlight lang=Matlab>
function r = align_columns(f)
function r = align_columns(f)
fid = fopen('align_column_data.txt', 'r');
fid = fopen('align_column_data.txt', 'r');
Line 5,775: Line 5,775:
end
end
end;
end;
</syntaxhighlight>
</lang>




Line 5,801: Line 5,801:
Note the presetting of P102 to indicate the alignment required.
Note the presetting of P102 to indicate the alignment required.


<lang ML/I>MCSKIP "WITH" NL
<syntaxhighlight lang=ML/I>MCSKIP "WITH" NL
"" Align columns - assumes macros on input stream 1, data on stream 2
"" Align columns - assumes macros on input stream 1, data on stream 2
MCPVAR 102
MCPVAR 102
Line 5,857: Line 5,857:
>
>
MCSET S1=1
MCSET S1=1
*MCSET S10=102</lang>
*MCSET S10=102</syntaxhighlight>


=={{header|ML/I}}==
=={{header|ML/I}}==
Line 5,863: Line 5,863:
Note the presetting of P102 to indicate the alignment required.
Note the presetting of P102 to indicate the alignment required.


<lang ML/I>MCSKIP "WITH" NL
<syntaxhighlight lang=ML/I>MCSKIP "WITH" NL
"" Align columns - assumes macros on input stream 1, data on stream 2
"" Align columns - assumes macros on input stream 1, data on stream 2
MCPVAR 102
MCPVAR 102
Line 5,919: Line 5,919:
>
>
MCSET S1=1
MCSET S1=1
*MCSET S10=102</lang>
*MCSET S10=102</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>columns(how) ; how = "Left", "Center" or "Right"
<syntaxhighlight lang=MUMPS>columns(how) ; how = "Left", "Center" or "Right"
New col,half,ii,max,spaces,word
New col,half,ii,max,spaces,word
Set ii=0
Set ii=0
Line 5,974: Line 5,974:
column are separated by at least one space.
column are separated by at least one space.
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</lang>
justified, right justified, or center justified within its column.</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>from strutils import splitLines, split
<syntaxhighlight lang=nim>from strutils import splitLines, split
from sequtils import mapIt
from sequtils import mapIt
from strfmt import format, write
from strfmt import format, write
Line 6,001: Line 6,001:
stdout.write(w.format align & $maxs[j])
stdout.write(w.format align & $maxs[j])
stdout.write "\n"
stdout.write "\n"
stdout.write "\n"</lang>
stdout.write "\n"</syntaxhighlight>
{{out}}
{{out}}
<pre>Left column-aligned output:
<pre>Left column-aligned output:
Line 6,031: Line 6,031:
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/align_columns.nit the official Nit’s repository]
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/align_columns.nit the official Nit’s repository]


<lang nit># Task: Align columns
<syntaxhighlight lang=nit># Task: Align columns
#
#
# Uses `Text::justify` from the standard library.
# Uses `Text::justify` from the standard library.
Line 6,079: Line 6,079:
aligner(text, 0.0)
aligner(text, 0.0)
aligner(text, 1.0)
aligner(text, 1.0)
aligner(text, 0.5)</lang>
aligner(text, 0.5)</syntaxhighlight>
{{out}}
{{out}}
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 6,103: Line 6,103:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
works with oo2c version 2.
works with oo2c version 2.
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE Columns;
MODULE Columns;
IMPORT
IMPORT
Line 6,212: Line 6,212:
END Columns.
END Columns.


</syntaxhighlight>
</lang>
<pre>
<pre>
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 6,239: Line 6,239:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>#load "str.cma"
<syntaxhighlight lang=ocaml>#load "str.cma"
open Str
open Str


Line 6,292: Line 6,292:
let sp2 = String.make pad2 ' ' in
let sp2 = String.make pad2 ' ' in
Printf.printf "%s%s%s " sp1 word sp2);
Printf.printf "%s%s%s " sp1 word sp2);
;;</lang>
;;</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang oforth>import: mapping
<syntaxhighlight lang=oforth>import: mapping
import: file
import: file


Line 6,316: Line 6,316:
0 #[ apply( #[ size max ] ) ] lines apply ->maxsize
0 #[ apply( #[ size max ] ) ] lines apply ->maxsize
#[ apply( #[ justify( maxsize , just) . ] ) printcr ] lines apply
#[ apply( #[ justify( maxsize , just) . ] ) printcr ] lines apply
;</lang>
;</syntaxhighlight>


{{out}}
{{out}}
Line 6,332: Line 6,332:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>
<syntaxhighlight lang=ooRexx>
text = .array~of("Given$a$text$file$of$many$lines,$where$fields$within$a$line$", -
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", -
"are$delineated$by$a$single$'dollar'$character,$write$a$program", -
Line 6,407: Line 6,407:
say out~string
say out~string
end
end
</syntaxhighlight>
</lang>
<pre>
<pre>
align left:
align left:
Line 6,438: Line 6,438:


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang progress>FUNCTION alignColumns RETURNS CHAR (
<syntaxhighlight lang=progress>FUNCTION alignColumns RETURNS CHAR (
i_c AS CHAR,
i_c AS CHAR,
i_calign AS CHAR
i_calign AS CHAR
Line 6,497: Line 6,497:
alignColumns( cc, "right" ) SKIP
alignColumns( cc, "right" ) SKIP
alignColumns( cc, "center" )
alignColumns( cc, "center" )
VIEW-AS ALERT-BOX.</lang>
VIEW-AS ALERT-BOX.</syntaxhighlight>


{{out}}
{{out}}
Line 6,662: Line 6,662:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang=oz>declare
%% Lines: list of strings
%% Lines: list of strings
%% Alignment: function like fun {Left Txt ExtraSpace} ... end
%% Alignment: function like fun {Left Txt ExtraSpace} ... end
Line 6,736: Line 6,736:
"justified,$right$justified,$or$center$justified$within$its$column."]
"justified,$right$justified,$or$center$justified$within$its$column."]
in
in
{ForAll {Align Lines Left} System.showInfo}</lang>
{ForAll {Align Lines Left} System.showInfo}</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
See [[Align_columns#Delphi | Delphi]]
See [[Align_columns#Delphi | Delphi]]
modified to {{works with|Free Pascal}}
modified to {{works with|Free Pascal}}
<lang pascal>program Project1;
<syntaxhighlight lang=pascal>program Project1;


{$H+}//Use ansistrings
{$H+}//Use ansistrings
Line 6,814: Line 6,814:
AlignByColumn(taCenter);
AlignByColumn(taCenter);
AlignByColumn(taRightJustify);
AlignByColumn(taRightJustify);
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,840: Line 6,840:


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>#/usr/bin/perl -w
<syntaxhighlight lang=Perl>#/usr/bin/perl -w
use strict ;
use strict ;


Line 6,895: Line 6,895:
}
}
print "\n" ;
print "\n" ;
}</lang>
}</syntaxhighlight>
a shorter solution
a shorter solution
<lang perl>use List::Util qw(max);
<syntaxhighlight lang=perl>use List::Util qw(max);


sub columns {
sub columns {
Line 6,920: Line 6,920:
Further,$allow$for$each$word$in$a$column$to$be$either$left$
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
justified,$right$justified,$or$center$justified$within$its$column.
END</lang>
END</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>-->
<!--<syntaxhighlight lang=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: #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>
<span style="color: #008000;">"Given$a$text$file$of$many$lines,$where$fields$within$a$line$"</span><span style="color: #0000FF;">,</span>
Line 6,991: Line 6,991:
<span style="color: #000000;">AlignColumns</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">AlignColumns</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 7,017: Line 7,017:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt


0 40 repeat var gap
0 40 repeat var gap
Line 7,062: Line 7,062:
0 alignWords nl
0 alignWords nl
1 alignWords nl
1 alignWords nl
drop</lang>
drop</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang=php><?php
$j2justtype = array('L' => STR_PAD_RIGHT,
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
'R' => STR_PAD_LEFT,
Line 7,111: Line 7,111:
echo aligner($textinfile, $j);
echo aligner($textinfile, $j);


?></lang>
?></syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>import util.
<syntaxhighlight lang=Picat>import util.


main =>
main =>
Line 7,160: Line 7,160:
Pad2 is Pad-Pad1,
Pad2 is Pad-Pad1,
printf("%*s%s%*s",Pad1,"",Word,Pad2,"").
printf("%*s%s%*s",Pad1,"",Word,Pad2,"").
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 7,188: Line 7,188:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(let Sizes NIL # Build a list of sizes
<syntaxhighlight lang=PicoLisp>(let Sizes NIL # Build a list of sizes
(let Lines # and of lines
(let Lines # and of lines
(make
(make
Line 7,208: Line 7,208:
(prinl)
(prinl)
(for L Lines
(for L Lines
(prinl (apply center L Sizes)) ) ) ) # and centered</lang>
(prinl (apply center L Sizes)) ) ) ) # and centered</syntaxhighlight>
{{out}}
{{out}}
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 7,232: Line 7,232:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>
<syntaxhighlight lang=PL/I>
declare text character (300) varying;
declare text character (300) varying;
declare word character (20) varying;
declare word character (20) varying;
Line 7,270: Line 7,270:
put file (output) skip;
put file (output) skip;
end;
end;
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>
<syntaxhighlight lang=PowerShell>
$file =
$file =
@'
@'
Line 7,296: Line 7,296:
}
}
$arr | Format-Table -HideTableHeaders -Wrap *
$arr | Format-Table -HideTableHeaders -Wrap *
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 7,309: Line 7,309:
=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog.
Works with SWI-Prolog.
<lang Prolog>aligner :-
<syntaxhighlight lang=Prolog>aligner :-
L ="Given$a$text$file$of$many$lines,$where$fields$within$a$line$
L ="Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 7,388: Line 7,388:
{N2 is N1 + 1},
{N2 is N1 + 1},
parse_word(T, N2, NF, TF).
parse_word(T, N2, NF, TF).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 7,420: Line 7,420:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{works with|PureBasic|4.41}}
{{works with|PureBasic|4.41}}
<lang PureBasic>Declare max(a,b)
<syntaxhighlight lang=PureBasic>Declare max(a,b)


If OpenConsole()
If OpenConsole()
Line 7,494: Line 7,494:
Data.s "Further,$allow$for$each$word$in$a$column$oo$be$either$left$"
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."
Data.s "justified,$right$justified,$or$center$justified$within$its$column."
EndDataSection</lang>
EndDataSection</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
===Procedural===
===Procedural===
====Using f-strings====
====Using f-strings====
<lang python>from itertools import zip_longest
<syntaxhighlight lang=python>from itertools import zip_longest


txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
Line 7,518: Line 7,518:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
print("- " * 52)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 7,550: Line 7,550:


====Using StringIO====
====Using StringIO====
<lang python>from StringIO import StringIO
<syntaxhighlight lang=python>from StringIO import StringIO
textinfile = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
textinfile = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 7,594: Line 7,594:
infile = StringIO(textinfile)
infile = StringIO(textinfile)
print "\n# %s Column-aligned output:" % align
print "\n# %s Column-aligned output:" % align
print aligner(infile, align[0])</lang>
print aligner(infile, align[0])</syntaxhighlight>


{{out}}
{{out}}
Line 7,625: Line 7,625:
Works with Python 2 and 3.
Works with Python 2 and 3.


<lang python>'''
<syntaxhighlight lang=python>'''
cat <<'EOF' > align_columns.dat
cat <<'EOF' > align_columns.dat
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 7,642: Line 7,642:
for row in rows:
for row in rows:
print(' '.join(fmts).format(*(row + [''] * len(fmts))))
print(' '.join(fmts).format(*(row + [''] * len(fmts))))
print('')</lang>
print('')</syntaxhighlight>




====Alternative====
====Alternative====
{{trans|D}}
{{trans|D}}
<lang python>txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
<syntaxhighlight 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
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 7,667: Line 7,667:
print(justify(word, max_widths[j]), end=' ')
print(justify(word, max_widths[j]), end=' ')
print()
print()
print("- " * 52)</lang>
print("- " * 52)</syntaxhighlight>


===Functional===
===Functional===
Line 7,675: Line 7,675:
(Selection of string justification methods via '''getattr'''):
(Selection of string justification methods via '''getattr'''):
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Variously aligned columns
<syntaxhighlight lang=python>'''Variously aligned columns
from delimited text.
from delimited text.
'''
'''
Line 7,749: Line 7,749:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 7,773: Line 7,773:


=={{header|q}}==
=={{header|q}}==
<lang q>text:(
<syntaxhighlight lang=q>text:(
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$";
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$";
"are$delineated$by$a$single$'dollar'$character,$write$a$program";
"are$delineated$by$a$single$'dollar'$character,$write$a$program";
Line 7,786: Line 7,786:
ps:$[aln=`R;-1-cw;1+cw]$''s; / padded strings
ps:$[aln=`R;-1-cw;1+cw]$''s; / padded strings
ps:$[aln=`C;(neg(cw-sl)div 2)rotate''ps;ps]; / center
ps:$[aln=`C;(neg(cw-sl)div 2)rotate''ps;ps]; / center
1,[;"\n\n"]"\n"sv raze each ps; } / print</lang>
1,[;"\n\n"]"\n"sv raze each ps; } / print</syntaxhighlight>
{{out}}
{{out}}
<pre>q)ta[`L]text
<pre>q)ta[`L]text
Line 7,814: Line 7,814:


=={{header|R}}==
=={{header|R}}==
<lang R># Read in text
<syntaxhighlight lang=R># Read in text
lines <- readLines(tc <- textConnection("Given$a$text$file$of$many$lines,$where$fields$within$a$line$
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
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 7,838: Line 7,838:
print0(leftjust)
print0(leftjust)
print0(rightjust)
print0(rightjust)
print0(centrejust)</lang>
print0(centrejust)</syntaxhighlight>
Right justified output shown.
Right justified output shown.
<div style="width:full;overflow:scroll"><pre>
<div style="width:full;overflow:scroll"><pre>
Line 7,850: Line 7,850:


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>
<syntaxhighlight lang=Racket>
#lang racket
#lang racket


Line 7,885: Line 7,885:
(display-aligned #:justify 'right text)
(display-aligned #:justify 'right text)
(display-aligned #:justify 'center text)
(display-aligned #:justify 'center text)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 7,893: Line 7,893:
Call with parameter left (default), center or right.
Call with parameter left (default), center or right.


<lang perl6>my @lines =
<syntaxhighlight lang=perl6>my @lines =
q|Given$a$text$file$of$many$lines,$where$fields$within$a$line$
q|Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 7,915: Line 7,915:
default { $word ~ " " x $lr }
default { $word ~ " " x $lr }
}
}
}</lang>
}</syntaxhighlight>


Or a more functional version, called like <code>./align.p6 left input.txt</code>, which however only supports left and right alignment (not center):
Or a more functional version, called like <code>./align.p6 left input.txt</code>, which however only supports left and right alignment (not center):


<lang perl6>sub MAIN ($alignment where 'left'|'right', $file) {
<syntaxhighlight lang=perl6>sub MAIN ($alignment where 'left'|'right', $file) {
my @lines := $file.IO.lines.map(*.split('$').cache).cache;
my @lines := $file.IO.lines.map(*.split('$').cache).cache;
my @widths = roundrobin(|@lines).map(*».chars.max);
my @widths = roundrobin(|@lines).map(*».chars.max);
Line 7,925: Line 7,925:
my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ "\n";
my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ "\n";
printf $format, |$_ for @lines;
printf $format, |$_ for @lines;
}</lang>
}</syntaxhighlight>


=={{header|RapidQ}}==
=={{header|RapidQ}}==
<syntaxhighlight lang=vb>
<lang vb>
Dim MText as QMemorystream
Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Line 7,970: Line 7,970:
TextCenter = TextCenter + Newline
TextCenter = TextCenter + Newline
next
next
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:20ex;overflow:scroll">TextLeft contains:
<pre style="height:20ex;overflow:scroll">TextLeft contains:
Line 7,998: Line 7,998:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>REBOL [
<syntaxhighlight lang=rebol>REBOL [
Title: "Align Columns"
Title: "Align Columns"
URL: http://rosettacode.org/wiki/Align_columns
URL: http://rosettacode.org/wiki/Align_columns
Line 8,055: Line 8,055:
foreach i [left centre right] [
foreach i [left centre right] [
print ["^/Align" i "...^/"] entable data get i]
print ["^/Align" i "...^/"] entable data get i]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 8,087: Line 8,087:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>Red [
<syntaxhighlight lang=Red>Red [
Title: "Align Columns"
Title: "Align Columns"
Original-Author: oofoe
Original-Author: oofoe
Line 8,145: Line 8,145:


foreach i [left centre right] [
foreach i [left centre right] [
print [newline "Align" i "..." newline] entable data get i]</lang>
print [newline "Align" i "..." newline] entable data get i]</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===(no output)===
===(no output)===
<lang rexx>/*REXX*/
<syntaxhighlight lang=rexx>/*REXX*/
z.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
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"
z.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
Line 8,197: Line 8,197:
end
end
say out
say out
end</lang>
end</syntaxhighlight>


===(with output)===
===(with output)===
<lang rexx>/*REXX program displays various alignments for words in an array of text strings. */
<syntaxhighlight 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. */
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$"
t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Line 8,229: Line 8,229:
say substr(_, 2) /*ignore the leading extra blank. */
say substr(_, 2) /*ignore the leading extra blank. */
end /*r*/
end /*r*/
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 8,261: Line 8,261:
===(boxed output)===
===(boxed output)===
Note: &nbsp; this version boxes each column of output to better show the columns.
Note: &nbsp; this version boxes each column of output to better show the columns.
<lang rexx>/*REXX program displays various alignments for words in an array of text strings. */
<syntaxhighlight 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. */
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$"
t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Line 8,297: Line 8,297:
end /*r*/ /* [↑] shows words in boxes. */
end /*r*/ /* [↑] shows words in boxes. */
say translate(bot, '┴', "┬") /*display the bottom line of the box. */
say translate(bot, '┴', "┬") /*display the bottom line of the box. */
end /*j*/ /*stick a fork in it, we're all done. */</lang>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 8,335: Line 8,335:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.9.3+}}
{{works with|Ruby|1.9.3+}}
<lang ruby>J2justifier = {Left: :ljust, Right: :rjust, Center: :center}
<syntaxhighlight lang=ruby>J2justifier = {Left: :ljust, Right: :rjust, Center: :center}


=begin
=begin
Line 8,378: Line 8,378:
puts aligner(infile, align)
puts aligner(infile, align)
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 8,408: Line 8,408:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang Runbasic>theString$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" _
<syntaxhighlight lang=Runbasic>theString$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" _
+ "are$delineated$by$a$single$'dollar'$character,$write$a$program" _
+ "are$delineated$by$a$single$'dollar'$character,$write$a$program" _
+ "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"_
+ "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"_
Line 8,446: Line 8,446:
wend
wend
print
print
end function</lang>
end function</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:15ex;overflow:scroll">------------ align:left -- across:6 ------------
<pre style="height:15ex;overflow:scroll">------------ align:left -- across:6 ------------
Line 8,486: Line 8,486:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::iter::{repeat, Extend};
<syntaxhighlight lang=rust>use std::iter::{repeat, Extend};


enum AlignmentType {
enum AlignmentType {
Line 8,549: Line 8,549:
println!("{}", repeat('-').take(110).collect::<String>());
println!("{}", repeat('-').take(110).collect::<String>());
println!("{}", align_columns(text, AlignmentType::Right));
println!("{}", align_columns(text, AlignmentType::Right));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:15ex;overflow:scroll">
<pre style="height:15ex;overflow:scroll">
Line 8,581: Line 8,581:
For Scala 2.7, change from fromPath to fromFile, and remove the extra parameter to Source's getLines.
For Scala 2.7, change from fromPath to fromFile, and remove the extra parameter to Source's getLines.


<lang scala>object ColumnAligner {
<syntaxhighlight lang=scala>object ColumnAligner {
val eol = System.getProperty("line.separator")
val eol = System.getProperty("line.separator")
def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)
def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)
Line 8,608: Line 8,608:
alignFile(filename, alignment) foreach println
alignFile(filename, alignment) foreach println
}
}
}</lang>
}</syntaxhighlight>


Another take:
Another take:


<lang scala>def pad(s:String, i:Int, d:String) = {
<syntaxhighlight lang=scala>def pad(s:String, i:Int, d:String) = {
val padsize = (i-s.length).max(0)
val padsize = (i-s.length).max(0)
d match {
d match {
Line 8,633: Line 8,633:
val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
padded map (_.reduceLeft(_ + _)) foreach println</lang>
padded map (_.reduceLeft(_ + _)) foreach println</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==


<lang scheme>
<syntaxhighlight lang=scheme>
(import (scheme base)
(import (scheme base)
(scheme write)
(scheme write)
Line 8,691: Line 8,691:
(align-columns *example* 'center)
(align-columns *example* 'center)
(align-columns *example* 'right)
(align-columns *example* 'right)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 8,723: Line 8,723:
=={{header|sed}}==
=={{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).
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).
<lang sed>
<syntaxhighlight lang=sed>
#!/bin/sed -nrf
#!/bin/sed -nrf
# Format: <master-pattern>\n<line1>\n<line1-as-pattern>\n<line2>\n<line2-as-pattern>...
# Format: <master-pattern>\n<line1>\n<line1-as-pattern>\n<line2>\n<line2-as-pattern>...
Line 8,799: Line 8,799:
bnextline
bnextline
}
}
</syntaxhighlight>
</lang>
Example:
Example:
<pre>
<pre>
Line 8,819: Line 8,819:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";


const array string: inputLines is [] (
const array string: inputLines is [] (
Line 8,870: Line 8,870:
writeln;
writeln;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 8,883: Line 8,883:


=={{header|Shiny}}==
=={{header|Shiny}}==
<lang shiny>text: 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
<syntaxhighlight 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
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 8,921: Line 8,921:
align text 'left'
align text 'left'
align text 'center'
align text 'center'
align text 'right'</lang>
align text 'right'</syntaxhighlight>


<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 8,945: Line 8,945:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>class Format(text, width) {
<syntaxhighlight lang=ruby>class Format(text, width) {
method align(j) {
method align(j) {
text.map { |row|
text.map { |row|
Line 8,991: Line 8,991:
say f.align(left);
say f.align(left);
say f.align(middle);
say f.align(middle);
say f.align(right);</lang>
say f.align(right);</syntaxhighlight>


=={{Header|Smalltalk}}==
=={{Header|Smalltalk}}==
the following works with Smalltalk/X, but should also in other dialects (may have to add "centerPadded" to the String class).
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 }}
{{works with |Smalltalk/X }}
<lang smalltalk>text :=
<syntaxhighlight lang=smalltalk>text :=
'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$''dollar''$character,$write$a$program
are$delineated$by$a$single$''dollar''$character,$write$a$program
Line 9,065: Line 9,065:


Stdout cr; printCR:'Centered with box:'.
Stdout cr; printCR:'Centered with box:'.
printCentered value:text value:true.</lang>
printCentered value:text value:true.</syntaxhighlight>
{{out}}
{{out}}
<pre>Left justified:
<pre>Left justified:
Line 9,138: Line 9,138:
=={{header|Snobol}}==
=={{header|Snobol}}==
{{works with|Snobol|4}}
{{works with|Snobol|4}}
<lang snobol>* Since we don't know how much text we'll be reading in,
<syntaxhighlight lang=snobol>* Since we don't know how much text we'll be reading in,
* we store the words and field widths in tables
* we store the words and field widths in tables
Words = TABLE()
Words = TABLE()
Line 9,230: Line 9,230:


END
END
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 9,259: Line 9,259:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun curry f x y = f (x, y)
<syntaxhighlight lang=sml>fun curry f x y = f (x, y)
fun uncurry f (x, y) = f x y
fun uncurry f (x, y) = f x y


Line 9,287: Line 9,287:
(* test stdin with all alignments *)
(* test stdin with all alignments *)
val () = print (String.concatWith "\n\n"
val () = print (String.concatWith "\n\n"
(map (formatTable (readTable TextIO.stdIn)) [alignL, alignC, alignR]) ^ "\n")</lang>
(map (formatTable (readTable TextIO.stdIn)) [alignL, alignC, alignR]) ^ "\n")</syntaxhighlight>
{{out}}
{{out}}
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 9,315: Line 9,315:
{{trans|Rust}}
{{trans|Rust}}


<lang swift>import Foundation
<syntaxhighlight lang=swift>import Foundation


extension String {
extension String {
Line 9,400: Line 9,400:
print(alignCols(input: input, align: .center))
print(alignCols(input: input, align: .center))
print()
print()
print(alignCols(input: input, align: .right))</lang>
print(alignCols(input: input, align: .right))</syntaxhighlight>


{{out}}
{{out}}
Line 9,428: Line 9,428:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang=tcl>package require Tcl 8.5


set text {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
set text {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 9,475: Line 9,475:
}
}
puts ""
puts ""
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Given a text file of many lines, where fields within a line
<pre>Given a text file of many lines, where fields within a line
Line 9,501: Line 9,501:
Transd has built-in support for "left" and "right" formatting, but not "centered", which added quite a bit of code.
Transd has built-in support for "left" and "right" formatting, but not "centered", which added quite a bit of code.


<lang scheme>#lang transd
<syntaxhighlight lang=scheme>#lang transd


MainModule : {
MainModule : {
Line 9,543: Line 9,543:
(lout "") (print true)
(lout "") (print true)
)
)
}</lang>{{out}}
}</syntaxhighlight>{{out}}
<pre>
<pre>
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 9,568: Line 9,568:


=={{header|TSE SAL}}==
=={{header|TSE SAL}}==
<lang TSESAL>
<syntaxhighlight lang=TSESAL>
INTEGER PROC FNBlockChangeColumnAlignLeftB( INTEGER columnTotalI, INTEGER spaceTotalI, INTEGER buffer1I )
INTEGER PROC FNBlockChangeColumnAlignLeftB( INTEGER columnTotalI, INTEGER spaceTotalI, INTEGER buffer1I )
INTEGER B = FALSE
INTEGER B = FALSE
Line 9,702: Line 9,702:
GotoBufferId( bufferI )
GotoBufferId( bufferI )
END
END
</syntaxhighlight>
</lang>
{{out}} <pre>
{{out}} <pre>
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 9,713: Line 9,713:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang=tuscript>
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
MODE DATA
MODE DATA
Line 9,736: Line 9,736:
ENDLOOP
ENDLOOP
SET exampletext=JOIN(new1,"$",new2,new3,new4,new5,new6,new7,new8,new9,new10,new11,new12)
SET exampletext=JOIN(new1,"$",new2,new3,new4,new5,new6,new7,new8,new9,new10,new11,new12)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 9,750: Line 9,750:
=={{header|TXR}}==
=={{header|TXR}}==


<lang txr>@(collect)
<syntaxhighlight lang=txr>@(collect)
@ (coll)@{item /[^$]+/}@(end)
@ (coll)@{item /[^$]+/}@(end)
@(end)
@(end)
Line 9,776: Line 9,776:
@{pi @(- [cw i] (trunc (- [cw i] (length pi)) 2))} @(end)
@{pi @(- [cw i] (trunc (- [cw i] (length pi)) 2))} @(end)
@ (end)
@ (end)
@(end)</lang>
@(end)</syntaxhighlight>


<pre>$ txr align-columns.txr align-columns.dat
<pre>$ txr align-columns.txr align-columns.dat
Line 9,800: Line 9,800:
=={{header|UNIX Shell}}==
=={{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.'')
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.'')
<lang bash>
<syntaxhighlight lang=bash>
cat <<EOF_OUTER > just-nocenter.sh
cat <<EOF_OUTER > just-nocenter.sh
#!/bin/sh
#!/bin/sh
Line 9,838: Line 9,838:
exit
exit
EOF_OUTER
EOF_OUTER
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<syntaxhighlight lang=sh>
<lang sh>
$ ./just-nocenter.sh
$ ./just-nocenter.sh
Given a text file of many lines, where fields within a line
Given a text file of many lines, where fields within a line
Line 9,855: Line 9,855:
Further, allow for each word in a column to be either left
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
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.''
The centered output will be added later, when I've more time. '' I did this in about 10 minutes.''
Line 9,862: Line 9,862:
Note that the left-justified case can be handled trivially by the <tt>column</tt> command, which ships with modern Linux and macOS systems:
Note that the left-justified case can be handled trivially by the <tt>column</tt> command, which ships with modern Linux and macOS systems:


<lang sh>tr '$' ' ' | column -t</lang>
<syntaxhighlight lang=sh>tr '$' ' ' | column -t</syntaxhighlight>


{{Out}}
{{Out}}
Line 9,879: Line 9,879:
For right justification, each word's string of trailing blanks is moved to the beginning,
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.
and for center justification, the trailing blanks are divided equally between the beginning and end of each word.
<lang Ursala>#import std
<syntaxhighlight lang=Ursala>#import std


text =
text =
Line 9,898: Line 9,898:
#show+
#show+


main = mat0 <.just_left,just_center,just_right> text</lang>
main = mat0 <.just_left,just_center,just_right> text</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:17ex;overflow:scroll">
<pre style="height:17ex;overflow:scroll">
Line 9,927: Line 9,927:
Both arguments are optional and default to "left" and 1 respectively.
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)
Public Sub TestSplit(Optional align As String = "left", Optional spacing As Integer = 1)
Dim word() As String
Dim word() As String
Line 9,993: Line 9,993:
Next l
Next l
End Sub
End Sub
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 10,017: Line 10,017:
=={{header|VBScript}}==
=={{header|VBScript}}==
{{trans|Rexx}}
{{trans|Rexx}}
<lang vb>' Align columns - RC - VBScript
<syntaxhighlight lang=vb>' Align columns - RC - VBScript
Const nr=16, nc=16
Const nr=16, nc=16
ReDim d(nc),t(nr), wor(nr,nc)
ReDim d(nc),t(nr), wor(nr,nc)
Line 10,079: Line 10,079:
xRTrim = cc
xRTrim = cc
End Function 'xRTrim
End Function 'xRTrim
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 10,109: Line 10,109:
=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
This implementation converts the file currently being edited. The file can then be saved with different filename if required.
This implementation converts the file currently being edited. The file can then be saved with different filename if required.
<lang vedit>RS(10, "$") // Field separator
<syntaxhighlight lang=vedit>RS(10, "$") // Field separator
#11 = 1 // Align: 1 = left, 2 = center, 3 = right
#11 = 1 // Align: 1 = left, 2 = center, 3 = right


Line 10,148: Line 10,148:
}
}
Line(1, ERRBREAK)
Line(1, ERRBREAK)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 10,176: Line 10,176:


=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
<lang vb>Sub AlignCols(Lines, Optional Align As AlignmentConstants, Optional Sep$ = "$", Optional Sp% = 1)
<syntaxhighlight 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)
Dim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0)
Line 10,191: Line 10,191:
Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), "", vbLf);
Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), "", vbLf);
Next i, j
Next i, j
End Sub</lang>
End Sub</syntaxhighlight>
Usage:<lang vb>Sub Main() 'usage of the above
Usage:<syntaxhighlight lang=vb>Sub Main() 'usage of the above
Const Text$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & vbLf & _
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 & _
"are$delineated$by$a$single$'dollar'$character,$write$a$program" & vbLf & _
Line 10,203: Line 10,203:
Debug.Print vbLf; "-- Center:": AlignCols Split(Text, vbLf), vbCenter
Debug.Print vbLf; "-- Center:": AlignCols Split(Text, vbLf), vbCenter
Debug.Print vbLf; "-- Right:": AlignCols Split(Text, vbLf), vbRightJustify
Debug.Print vbLf; "-- Right:": AlignCols Split(Text, vbLf), vbRightJustify
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>-- Left:
<pre>-- Left:
Line 10,230: Line 10,230:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vb>Module Module1
<syntaxhighlight lang=vb>Module Module1
Private Delegate Function Justification(s As String, width As Integer) As String
Private Delegate Function Justification(s As String, width As Integer) As String


Line 10,294: Line 10,294:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>


{{out}}
{{out}}
Line 10,323: Line 10,323:
=={{header|Vlang}}==
=={{header|Vlang}}==
Currently (5/2022) 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
Currently (5/2022) 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
<lang vlang>
<syntaxhighlight lang=vlang>
const text = "Given\$a\$text\$file\$of\$many\$lines,\$where\$fields\$within\$a\$line\$
const text = "Given\$a\$text\$file\$of\$many\$lines,\$where\$fields\$within\$a\$line\$
are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program
are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program
Line 10,391: Line 10,391:
f.print(Justify.middle)
f.print(Justify.middle)
f.print(Justify.right)
f.print(Justify.right)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 10,419: Line 10,419:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "io" for File
<syntaxhighlight lang=ecmascript>import "io" for File
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 10,472: Line 10,472:
var fileName = "align_cols.txt"
var fileName = "align_cols.txt"
var lines = getLines.call(fileName)
var lines = getLines.call(fileName)
for (i in 0..2) alignCols.call(lines, i)</lang>
for (i in 0..2) alignCols.call(lines, i)</syntaxhighlight>


{{out}}
{{out}}
Line 10,503: Line 10,503:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|Run BASIC}}
{{trans|Run BASIC}}
<lang yabasic>theString$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
<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$ + "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$ + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
Line 10,569: Line 10,569:
wend
wend
print
print
end sub</lang>
end sub</syntaxhighlight>
{{out}}
{{out}}
<pre>Same as Run BASIC entry.</pre>
<pre>Same as Run BASIC entry.</pre>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn format(text,how){
<syntaxhighlight lang=zkl>fcn format(text,how){
words:=text.split("$").apply("split").flatten();
words:=text.split("$").apply("split").flatten();
max:=words.reduce(fcn(p,n){ n=n.len(); n>p and n or p },0);
max:=words.reduce(fcn(p,n){ n=n.len(); n>p and n or p },0);
Line 10,589: Line 10,589:
do{ w.pump(wordsPerCol,d,fmt).append("\n") } while(not w.atEnd);
do{ w.pump(wordsPerCol,d,fmt).append("\n") } while(not w.atEnd);
d.text;
d.text;
}</lang>
}</syntaxhighlight>
<lang zkl>text:=
<syntaxhighlight lang=zkl>text:=
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n"
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n"
Line 10,600: Line 10,600:
format(text,-1).print();
format(text,-1).print();
format(text, 0).print();
format(text, 0).print();
format(text, 1).print();</lang>
format(text, 1).print();</syntaxhighlight>
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.
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}}
{{out}}
Line 10,637: Line 10,637:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
The max width (without 'hack') of ZX Spectrum screen is 32 characters. The text sample is adapted for this feature.
The max width (without 'hack') of ZX Spectrum screen is 32 characters. The text sample is adapted for this feature.
<lang zxbasic> 5 BORDER 2
<syntaxhighlight lang=zxbasic> 5 BORDER 2
10 DATA 6
10 DATA 6
20 DATA "The$problem$of$Speccy$"
20 DATA "The$problem$of$Speccy$"
Line 10,683: Line 10,683:
3090 NEXT i
3090 NEXT i
3095 PRINT
3095 PRINT
3100 RETURN</lang>
3100 RETURN</syntaxhighlight>


{{out}}Left alignement example:
{{out}}Left alignement example: