Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Rust string in a number of characters

Tags:

format

rust

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--------

like image 981
D. Ataro Avatar asked Feb 05 '23 09:02

D. Ataro


1 Answers

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.

like image 151
Shepmaster Avatar answered Feb 08 '23 14:02

Shepmaster