Logo

Programming-Idioms

  • Perl

Idiom #216 Pad a string on both sides

Add the extra character c at the beginning and ending of string s to make sure its length is at least m.
After the padding the original content of s should be at the center of the result.
The length is the number of characters, not the number of bytes.

E.g. with s="abcd", m=10 and c="X" the result should be "XXXabcdXXX".

use feature 'signatures';
my $total_padding = $m-length($s);
if( $total_padding ) {
   my $l = int($total_padding/2);
   my $r = $total_padding-$l;
   $s = join "", ($c x $l), $s, ($c x $r);
}
sub center {
    my ($s, $m, $c) = @_;
    my $slen = length $s;
    return $s if $slen > $m;
    $c //= ' ';
    my $r = $c x $m;
    my $p = int($m/2 - $slen/2);
    substr($r, $p, $slen, $s);
    return $r;    
}

print center("abcd",10,"X");

Create a string of length $m by repeating $c. Calculate the midpoint of $m and of $s and use that to calculate the position $s should start in $m. Use substr to substitute $s into $m. $c is optional, default to space. If the length of $s > $m then $s is returned. Using substr is ~4% faster than string concatenate, and ~13% faster than join.
  i = (m-len(s))/2
  j = (m - len(s)) - (m-len(s))/2
  s = repeat(c,i) // s // repeat(c,j)

New implementation...
< >
Bart