Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #216 Pad a string in the center

Prepend 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".

LazUtf8
s := UTF8PadCenter(s,m,c);
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);
}
s = s.center(m, c)
 s.center(m,c)

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

Bart

Related idioms