Search code examples
rustvectorpretty-print

How to pretty print a Vec<char> with separator?


I am trying to apply join (or something similar) to a Vec<char> in order to pretty print it.

What I came up with so far is this (and this does what I want):

let vec: Vec<char> = "abcdef".chars().collect();
let sep = "-";
let vec_str: String = vec
    .iter().map(|c| c.to_string()).collect::<Vec<String>>().join(sep);
println!("{}", vec_str);  // a-b-c-d-e-f

That seems overly complex (and allocates a Vec<String> that is not really needed).

I also tried to get std::slice::join to work by explicitly creating a slice:

let vec_str: String = (&vec[..]).join('-');

but here the compiler complains:

method not found in &[char]

Is there a simpler way to create a printable String from a Vec<char> with a separator between the elements?


Solution

  • You can use intersperse from the itertools crate.

    use itertools::Itertools; // 0.8.2
    
    fn main() {
        let vec : Vec<_> = "abcdef".chars().collect();
        let sep = '-';
        let sep_str : String = vec.iter().intersperse(&sep).collect();
        println!("{}", sep_str);
    }
    

    Playground