Logo

Programming-Idioms

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

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");
  i = (m-len(s))/2
  j = (m - len(s)) - (m-len(s))/2
  s = repeat(c,i) // s // repeat(c,j)
import "encoding/utf8"
import "strings"
n := (m-utf8.RuneCountInString(s)+1)/2
if n > 0 {
	pad := strings.Repeat(string(c), n)	
	s = pad + s + pad
}
if(s.length() < m) {
    String x = String.valueOf(c).repeat(m - s.length());
    s = x.substring(0, x.length() / 2) + s + x.substring(x.length() / 2);
}
uses LazUtf8;
s := UTF8PadCenter(s,m,c);
s = s.center(m, c)
s = s.center(m, c)
use pad::{Alignment, PadStr};
// with const char, for example '!'
let n = (m + s.len())/2;
let out = format!("{s:!>n$}");
let out = format!("{out:!<m$}");

// with c char
let out = s.pad(m, c, Alignment::Middle, true);

New implementation...
< >
Bart