Logo

Programming-Idioms

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

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 pad::{Alignment, PadStr};
s = s.pad(m, c, Alignment::Middle, true);
let n = (m + s.len())/2;
s = format!("{s:X>n$}");
s = format!("{out:X<m$}");

Here c has constant value "X", written in the pattern.

This does not work with a variable c.

s is a String.
  i = (m-len(s))/2
  j = (m - len(s)) - (m-len(s))/2
  s = repeat(c,i) // s // repeat(c,j)

New implementation...
< >
Bart