How to pad a string on the left in Rust

2 Answers

0 votes
fn main() {
    let original = "Rust";
    
    let padded = format!("{:>7}", original); // Right-align in 7-character field
    
    println!("'{}'", padded); 
}

 
 
/*
run:
   
'   Rust'

*/
 

 



answered Jul 4 by avibootz
0 votes
fn pad_left(s: &str, total_len: usize, pad_char: char) -> String {
    let pad_len = total_len.saturating_sub(s.len());
    
    format!("{}{}", pad_char.to_string().repeat(pad_len), s)
}

fn main() {
    let padded = pad_left("Rust", 7, '*');
    
    println!("{}", padded); 
}

 
 
/*
run:
   
***Rust

*/
 

 



answered Jul 4 by avibootz
...