I have been reading up on format!
and all of the formatting options and saw there was a beautiful way of centering a string of text using either <
, ^
or >
. Rather than centering a string in whitespace, is it possible to center it in a character?
{:^32} // Centers it nicely in 32 characters of whitespace
I was thinking something like:
{:^32'c'} // But this does not work
I have tried almost every way thinkable, except those that seem way too crazy. But luckily there is Stack Overflow!
Is it possible to center a string using numbers to achieve something like the following?
--------SO is AWESOME--------
Is it possible to center a string using numbers to achieve something like the following?
Yes, kind of, as long as you truly mean "something like"...
fn main() {
let s = format!("{:-^30}", "SO is AWESOME");
assert_eq!(s, "--------SO is AWESOME---------");
// ^-- 8 here ^-- 9 here
}
Referring to the formatting syntax, here's the relevant parts:
format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type]
fill := character
align := '<' | '^' | '>'
width := count
We specify a fill (-
), an alignment (^
/ center), and a width (30
). However, the string is 13 units wide, so to pad it out to 30 units, the fill has to be bigger on one side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With