g | x | w | all
Bytes Lang Time Link
086AWK250826T154100Zxrs
404Pascal230904T200011ZKai Burg
025APL Dyalog Extended200910T075321ZRazetime
001Japt190320T124457ZShaggy
00205AB1E190320T120453ZKevin Cr
058PowerShell151216T060839ZTessella
098PHP190122T182238Z640KB
025Japt151218T030226ZETHprodu
081Python 2151216T044420ZWillem
335LabVIEW151216T091115ZEumel
061Perl 6151216T173440ZBrad Gil
040HTML151217T223753ZNeil
126R151217T171145ZMutador
077Haskell151216T190917Zbasile-h
061Ruby151216T093013Zmanatwor
019CJam151216T021709ZNinjaBea
nanFunciton151217T024927ZTimwi
017Pyth151216T014825Zizzyg
022MATL151216T085033ZLuis Men
052Retina151216T091625ZMartin E
035vim151216T023443ZDoorknob
091JavaScript ES6151216T042237Zuser8165
160Gema151216T105813Zmanatwor
203Emacs Lisp151216T075020ZLord Yuu
024TeaScript151216T044433ZDowngoat
003Jolf151216T034833ZConor O&
096Mathematica151216T014943ZLegionMa

AWK, 86 bytes

a[++k]=$0{(l[k]=length())>n&&n=l[k]}END{for(;i++<k;)printf"%*s%s\n",(n-l[i])/2,X,a[i]}

Attempt This Online!

Pascal, 404 bytes

This complete program is suitable for any processor complying with ISO standards 7185 (“Standard Pascal”) or 10206 (“Extended Pascal”). The maximumLineLength algorithm requires that every line has a maximum length of maxInt characters.

program p(input,output);type Z=integer;var b:text;l:file of Z;c,m:Z;begin
m:=0;c:=0;rewrite(b);rewrite(l);while not EOF do begin if EOLn then begin
write(l,c);c:=0;writeLn(b)end else begin c:=c+1;if c>m then
m:=c;write(b,input^)end;get(input)end;reset(b);reset(l);while not EOF(b)do
begin read(l,c);for c:=1 to(m-c)div 2 do write(' ');while not EOLn(b)do
begin write(b^);get(b)end;writeLn;get(b)end end.

Ungolfed:

program centerTheText(input, output);
    type
        integerNonNegative = 0‥maxInt;
    
    var
        { The behavior of `reset(input)` is implementation-defined.
          Using a buffer `text` file avoids relying on specific behavior. }
        buffer: text;
        { Stores the length of a line in `input` (buffered in `buffer`). }
        lineLength: file of integerNonNegative;
        { The length of the currently processed line. }
        currentLineLength: integerNonNegative;
        { The length of the longest line found. }
        maximumLineLength: integerNonNegative;
    
    begin
        maximumLineLength ≔ 0;
        currentLineLength ≔ 0;
        { Open files for writing and set their lengths to zero (“truncate”). }
        rewrite(buffer);
        rewrite(lineLength);
        
        { process and analyze `input` ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ }
        while not EOF(input) do
        begin
            { Invocation of `EOLn(input)` is only valid if `not EOF(input)`. }
            if EOLn(input) then
            begin
                { `input↑` contains a space so we cannot just copy it. }
                writeLn(buffer);
                { Store the determined line length for the centering. }
                write(lineLength, currentLineLength);
                { Prepare `currentLineLength` for the next line. }
                currentLineLength ≔ 0;
            end
            else
            begin
                currentLineLength ≔ currentLineLength + 1;
                { In Extended Pascal you could write: `maximumLineLength ≔
                  card([0‥currentLineLength, 0‥maximumLineLength]) − 1`. }
                if currentLineLength > maximumLineLength then
                begin
                    maximumLineLength ≔ currentLineLength;
                end;
                { For later reference store `input↑` in `buffer`. }
                write(buffer, input↑);
            end;
            { Advance reading cursor. }
            get(input);
        end;
        
        { Open files for reading from the start. }
        reset(buffer);
        reset(lineLength);
        
        { Reproduce `input` but centered. ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ }
        while not EOF(buffer) do
        begin
            read(lineLength, currentLineLength);
            { In Extended Pascal you could also just write:
              `write('':(maximumLineLength − currentLineLength) div 2)` }
            for currentLineLength ≔ 1 to
                (maximumLineLength − currentLineLength) div 2 do
            begin
                write(output, ' ');
            end;
            { Do not enter loop in case of an empty line. }
            while not EOLn(buffer) do
            begin
                write(output, buffer↑);
                get(buffer);
            end;
            { Discard the end-of-line marker character. }
            get(buffer);
            { Emit the implementation-specific end-of-line marker character. }
            writeLn(output);
        end;
    end.

Extended Pascal, 252 bytes

Requiring a processor compliant with ISO standard 10206 “Extended Pascal” the schema data type string becomes available. Lots of operations can be thus abbreviated:

program p(input,output);var b:text;l:string(maxInt);m:integer;begin
m:=0;rewrite(b);while not EOF do begin readLn(l);if m<length(l)then
m:=length(l);writeLn(b,l)end;reset(b);while not EOF(b)do begin
readLn(b,l);writeLn('':(m-length(l))div 2,l)end end.

Ungolfed:

program centerTheText(input, output);
    type
        { `integer…` prefix to facilitate sorting in documentation tools. }
        integerNonNegative = 0‥maxInt;
    
    var
        buffer: text;
        line: string(maxInt);
        maximumLineLength: integerNonNegative value 0;
    
    begin
        { The size of `buffer` immediately becomes zero. }
        rewrite(buffer);
        { Find the length of the longest line in `input`. }
        while not EOF(input) do
        begin
            readLn(input, line);
            { Is the current line longer than the longest line so far? }
            if length(line) > maximumLineLength then
            begin
                maximumLineLength ≔ length(line);
            end;
            { Store the read `input` line in `buffer` for later retrieval. }
            writeLn(buffer, line);
        end;
        
        { (Re‑)open `buffer` and start reading `buffer` from the start. }
        reset(buffer);
        { The `while` loop is not entered in case `buffer` is an empty file. }
        while not EOF(buffer) do
        begin
            readLn(buffer, line);
            { Empty strings (`''`) are only allowed in Extended Pascal.
              For `string` values the `integer` expression after the colon
              dictates the _exact_ width of the string padded with spaces. }
            writeLn('':(maximumLineLength − length(line)) div 2, line);
        end;
    end.

APL (Dyalog Extended), 25 bytes

{↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵}

There's an APLcart snippet for centering in a field:

Is(⊢↑⍨∘-∘⌊2÷⍨+∘≢)Dv

This answer is partly based on it.

Try it online!

Explanation

{↑(-⌊((⌈/≢¨⍵)+≢¨⍵)÷2)↑¨⍵}
      (⌈/≢¨⍵)             Maximum of lengths of each line
             +≢¨⍵         Plus length of each line
     (           )÷2      divided by two
   -⌊(           )        Floor it, and take negative
  (                 )↑¨⍵  Take that much from each line
                          (taking a negative value prepends spaces)
 ↑                        Mix the final array to print on each line
{                       } dfn

Japt, 1 byte

û

Try it or run all test cases

05AB1E, 2 bytes

.c

Builtins ftw ¯\_(ツ)_/¯

Try it online or verify all test cases.

Explanation:

.c   # Centralize the (implicit) multi-line input-string with preference to the left
     # (output the result implicitly)

(Preference to the right would be with a capital .C instead: see the differences.)

PowerShell, 58 67 bytes

down to 58 bytes thanks to @mazzy's comments:

param($a)$a|%{$_|% *ft(($a|% le*|sort)[-1]/2+$_.length/2)}


# It takes an array of strings as input
PS C:\Temp> .\center.ps1 'aaa','bb','c'
aaa
bb
 c


# Or here, read from a file
PS C:\Temp> .\center.ps1 (gc t.txt)
info0:info1:info2:info3
      info0:info1
          ttt
          tt
           t

PHP, 98 bytes

function($s){foreach($a=explode("
",$s)as$l)echo str_pad($l,max(array_map(strlen,$a)),' ',2),"
";}

Try it online!

Ungolfed:

function str_center( $s ) {
    $a = explode( PHP_EOL, $s );
    $m = max( array_map( 'strlen', $a ) );
    foreach( $a as $l ) {
        echo str_pad( $l, $m, ' ', STR_PAD_BOTH ), PHP_EOL;
    }
}

Output:

Programming Puzzles
         &         
     Code Golf   

Japt, 28 25

¡V=VwXl}R;¡Sp½*(V-Xl¹+X}R

Try it online!

How it works

¡     V=VwXl}R;¡     Sp½*(V-Xl¹ +X}R
UmXYZ{V=VwXl}R;UmXYZ{Sp½*(V-Xl) +X}R

           // Implicit: U = input string, V = 0
UmXYZ{  }  // Map each item X in U through this function,
         R // splitting U at newlines beforehand:
  V=VwXl   //  Set V to max(X, Y.length).
           // V is now set to the length of the longest line.

UmXYZ{  }  // Map each item X in U with this function,
         R // again splitting U at newlines beforehand:
 ½*(V-Xl)  //  Take V minus X.length, and multiply by 1/2.
Sp         //  Repeat a space that many times.
        +X //  Concatenate X to the end.

Python 2, 83 81 bytes

def f(s):
 t=s.split('\n')
 for y in t:print(max(len(f)for f in t)-len(y))/2*' '+y  

Thanks to @xnor for saving 2 chars

example input:

f("""Programming Puzzles
&
Code Golf""")

example output:

Programming Puzzles
         &
     Code Golf

And ending in second place with 84 bytes using str.center() and str.rstrip (thanks @J F).

def f(s):
 t=s.split('\n')
 for y in t:print y.center(max(len(f)for f in t)).rstrip()

LabVIEW, 3 or 35 LabVIEW Primitives

Finds lines until none are left, then calculates how many spaces to add and puts everything together.

Alternatively you could use the built-in center alignment on string indicators, it kinda does feel like cheating though.

Perl 6, 61 bytes

$/=(my@l=lines)».chars.max;for @l {put ' 'x($/-.chars)/2~$_} # 61 bytes

usage:

$ perl6 -e '$/=(my@l=lines)».chars.max;for @l {put " "x($/-.chars)/2~$_}' <<< \
'Programming Puzzles
&
Code Golf'
Programming Puzzles
         &
     Code Golf

HTML, 40 bytes

<xmp style=float:left;text-align:center>

<xmp style=float:left;text-align:center>
Programming Puzzles
&
Code Golf
</xmp>

Snippet includes </xmp> tag because the code snippet viewer wants my tags to be balanced.

R, 126 bytes

code

for(z in 1){l=scan(,"");m=sapply(l,nchar);t=max(m[m==max(m)]);for(i in 1:length(m))cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="")}

ungolfed

for(z in 1){                          # any way to get rid of this?
  l=scan(,"")
  m <- sapply(l,nchar)
  t <- max(m[m==max(m)])
  for(i in 1:length(m)){
    cat(rep(" ",(t-m[i])/2),l[i],"\n", sep="")
  }
}

Probably there are waay better ways to do this, still working on it.

Haskell, 111 81 77 bytes

l=length
f s|q<-lines s=unlines[([1..div(maximum(l<$>q)-l w)2]>>" ")++w|w<-q]

Input to the f function, the output is not printed.

Usage: load in interpreter ghci center.hs and then if you want to print the output of f on a given string putStr$f"Programming Puzzles\n&\nCode Golf"

Edit: Thanks to nimi for 34 bytes, great job! :D

Ruby, 76 68 61 bytes

->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}}

Sample run:

2.1.5 :001 > puts ->t{(s=t.split$/).map{|l|l.center(s.map(&:size).max).rstrip}}["Programming Puzzles\n&\nCode Golf"]
Programming Puzzles
         &
     Code Golf

CJam, 26 23 19 bytes

qN/_z,f{1$,m2/S*\N}

My first time using CJam! Four bytes saved thanks to Martin Büttner. Try it online.

Explanation

qN/    e# Read input and split each line
_z,    e# Transpose a copy and get its length to find the longest line
f{     e# For each line...
  1$,- e# Subtract its length from the longest length
  2/   e# Divide by two to get just the spaces to add to the left
  S*\  e# Add a string with that many spaces to the beginning
  N    e# Add a newline to go on to the next line
}

Funciton, non-competitive

This challenge has highlighted the sore lack of a “maximum value” (and minimum value) function for lazy sequences, so... I added them to the core library (they’re called ⊤ and ⊥, respectively). Therefore I didn’t bother to submit this as a golfed answer (it would have to include the ⊤ function declaration to be valid), so here’s just the main program.

Execute (function(){$('pre,code').css({lineHeight:5/4,fontFamily:'DejaVu Sans Mono'});})() in your browser console to get some nicer rendering.

   ╓───╖         ╔════╗  ┌───╖  ╔═══╗
 ┌─╢ ‡ ╟─┐       ║ 10 ╟──┤ ǁ ╟──╢   ║
 │ ╙───╜ │       ╚════╝  ╘═╤═╝  ╚═══╝
 │ ┌───╖ │  ┌──────────────┴──────────────────┐
 └─┤ ‼ ╟─┘┌─┴─╖ ┌───╖ ┌───╖ ┌───╖ ┌───╖       │     │
   ╘═╤═╝  │ ɱ ╟─┤ ⊤ ╟─┤ + ╟─┤ ~ ╟─┤ ℓ ╟───┐ ┌─┴─╖ ┌─┴─╖ ╔════╗
     │    ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╘═══╝ ╘═══╝   │ │ ɱ ╟─┤ ʝ ╟─╢ 10 ║
    ┌───╖ ╔═╧═╕ ╔═══╗ ┌─┴──╖ ┌───╖ ╔════╗ │ ╘═╤═╝ ╘═══╝ ╚════╝
  ┌─┤ ℓ ╟─╢   ├─╢ 1 ║ │ >> ╟─┤ … ╟─╢ 32 ║ │   │
  │ ╘═══╝ ╚═╤═╛ ╚═╤═╝ ╘═╤══╝ ╘═╤═╝ ╚════╝ │ ╔═╧═╕ ╔═══╗
  └─────────┘     └─────┘      │   ┌───╖  ├─╢   ├─╢ 0 ║
                               └───┤ ‡ ╟──┘ ╚═╤═╛ ╚═══╝
                                   ╘═╤═╝      │
                                     └────────┘

Explanation

I believe this may be the first Funciton answer on this site that uses lambda expressions.

Pyth, 19 17 bytes

2 bytes thanks to Jakube

V.ztr+1.[l.T.zNd6

Demonstration

I think this is the first time the center-pad function of .[ has been useful. The length of the longest line is found using non-truncating transpose (.T).

Trailing spaces are removed by adding a non-space character to the front, stripping spaces, then removing the added character.

MATL, 22 31 bytes

`jtYz~]xXhc4X4H$ZuZ{Zv

Each line is input with a trailing line (that is, an enter keystroke). An empty line (two enter keystrokes) marks the end of input.

Example

>> matl `jtYz~]xXhc4X4H$ZuZ{Zv
> foo
> barbaz
> 
 foo
barbaz

Explanation

`          % do...
  j        % input one string
  tYz~     % is it not empty?
]          % ...while
x          % delete last input (empty string)
Xh         % concatenate all inputs into a cell array
c          % convert to char (2D array). This fills with spaces to the right
4X4H$Zu    % center justify
Z{         % convert to cell array of strings
Zv         % remove trailing blanks of each string

Retina, 54 52 bytes

+m`^(.)+$(?<=(?=[^\t]*^..(?<-1>.)+(?(1)^))[^\t]*)
 $0 

The \ts can replaced with actual tabs, but I've used \t here, because otherwise SE will convert the tabs to spaces. Note that there is a leading space on the second line.

Try it online.

Explanation

The basic idea is to match a line which is at least two characters shorter than the longest line (or technically, two characters shorter than any other line), and surround it in two spaces. This is repeated until we can no longer find such a line, which means that all lines are within one character of the maximum length (where the one character is to account for parity mismatches, and guarantees that these lines are shifted to the left off-centre).

As for the actual regex:

^(.)+$

Just matches any one line while pushing one capture onto group 1 for each character.

(?<=...[^\t]*)

Is a lookbehind which is matched right-to-left and moves the cursor to the beginning of the string, so that the lookahead inside can check the entire string. Note that due to a lack of an anchor, the lookahead could be applied from anywhere else, but that does not create additional matches. We know that [^\t] will always match any character in the string, because the input is guaranteed to contain only spaces and linefeeds as far as whitespace is concerned.

(?=[^\t]*^..(?<-1>.)+(?(1)^))

This lookahead tries to find a line which is at least two characters longer than the one we're currently matching. [^\t]* moves through the string in order to be able to match any line. ^ ensures that we're starting from the beginning of the line. .. then matches the two additional characters we require for the longer line. Now (?<-1>.)+ matches individual characters in that line while popping from group 1 (note that . cannot match a linefeed, so this is constrained to one line). Finally, (?(1)^) asserts that we managed to empty the entire group 1. If the line is shorter than required, this is not possible, because there are not enough characters in the line to pop from group 1 often enough to empty it.

vim, 43 36 35 bytes

VGrx:sor
G:let &tw=col("$")
uu:%ce

Too good not to post. Note the trailing newline; it is significant.

Thanks to @Marth for saving a character!

vim-friendly format:

VGrx:sor<cr>G:let &tw=col("$")<cr>uu:%ce<cr>

Explanation:

VGrx                   replace every character with an "x"
:sor<cr>               sort (since all chars are now same, sorts by line length)
G                      go to the very last line
:let &tw=col("$")<cr>  set &tw to column number of last char on this line
                         "let &tw" is equivalent to "set tw"
                         tw is short for textwidth, used in :center
uu                     undo the sort, and the replacing-with-x too
:%ce<cr>               center over entire file (%), using textwidth set earlier

JavaScript (ES6), 93 91 bytes

s=>(m=l=s.split`
`).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join`
`

2 bytes saved thanks to @edc65!

Explanation

s=>(
  m=                // m = max line length (divided by 2)
    l=s.split`
`)                  // l = array of lines
.map(x=>            // for each line
  (v=x.length/2)    // v = current line length / 2
    <m?v:m=v        // set m to the max line length and return v
)
.map((x,i)=>        // for each line length / 2
  " ".repeat(m-x)   // add spaces before
    +l[i]           // add line text
)
.join`
`                   // return lines as a newline-separated string

Test

var solution = s=>(m=l=s.split`
`).map(x=>(v=x.length/2)<m?v:m=v).map((x,i)=>" ".repeat(m-x)+l[i]).join`
`
<textarea id="input" rows="4" cols="20">Programming Puzzles
&
Code Golf</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>

Gema, 160 bytes

\L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}}
?=
\Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o

Written mostly for my curiosity to see what can be done in a language without proper array structure and proper loop instruction.

Sample run:

bash-4.3$ gema '\L<T>=@push{i;$0}@set{m;@cmpn{@length{$0};${m;};$m;$m;@length{$0}}};?=;\Z=@repeat{@sub{@line;1};@set{o;@right{@div{@add{$m;@length{$i}};2};$i}\n${o;}}@pop{i}}$o' <<< $'Programming Puzzles\n&\nCode Golf'
Programming Puzzles
         &
     Code Golf

Emacs Lisp, 203 bytes

(let((f 0)(l 0))(dolist(s(split-string(buffer-string)"\n"))(set'l(string-width s))(when(> l f)(set'f l)))(let((fill-column f))(goto-char(point-min))(while(<(point)(point-max))(center-line)(next-line)))))

Ungolfed:

(let ((f 0) (l 0))
  (dolist (s (split-string(buffer-string) "\n"))
    (set 'l (string-width s))
    (when (> l f)
      (set 'f l)))
    (let ((fill-column f))
      (goto-char (point-min))
      (while (< (point) (point-max))
        (center-line)
        (next-line)))))

Centered:

               (let ((f 0) (l 0))
 (dolist (s (split-string(buffer-string) "\n"))
           (set 'l (string-width s))
                 (when (> l f)
                  (set 'f l)))
             (let ((fill-column f))
            (goto-char (point-min))
         (while (< (point) (point-max))
                 (center-line)
                (next-line)))))

TeaScript, 24 bytes

£p.R((aßln)¯-ln)/2)+l,§)

Loops through lines, adds floor((max line length - line length) / 2) spaces to the beginning.

Ungolfed

£   p.R((aß  ln)¯  -ln)/2)+l,§   )
xl(#p.R((am(#ln)X()-ln)/2)+l,`\n`)

xl(#    // Loops through newlines
    p.R(   // Repeats spaces
      (
       am(#ln)    // Map all line lengths
              X() // Get largest line length
       -ln)       // Subtract current line length
      /2)  // Divide by two
      +l,  // Add current line text
`\n`)

Try it online

Jolf, 3 bytes

Noncompeting, update postdates question.

Try it here!.

pci
pc  center
  i  string input

¯\_(ツ)_/¯ I thought it'd be a useful function.

Mathematica, 96 bytes

StringRiffle[#~StringPadLeft~Floor[Max@(l=StringLength)@a/2+l@#/2]&/@(a=#~StringSplit~"
"),"
"]&

Don't ask me how it worked, I just fiddled with it until it produced the correct output.