How to pad a string on both sides in Rust

1 Answer

0 votes
fn pad_both(s: &str, total_len: usize, pad_char: char) -> String {
    if s.len() >= total_len {
        return s.to_string();
    }
    
    let pad_total = total_len - s.len();
    let pad_left = pad_total / 2;
    let pad_right = pad_total - pad_left;
    
    format!(
        "{}{}{}",
        pad_char.to_string().repeat(pad_left),
        s,
        pad_char.to_string().repeat(pad_right)
    )
}

fn main() {
    println!("'{}'", pad_both("Rust", 9, ' '));
    println!("{}", pad_both("Rust", 9, '*'));
}

 
 
/*
run:
   
'  Rust   '
**Rust***

*/

 



answered Jul 6 by avibootz

Related questions

2 answers 56 views
2 answers 63 views
1 answer 58 views
1 answer 51 views
1 answer 46 views
1 answer 48 views
...