0

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?

Boiethios
  • 38,438
  • 19
  • 134
  • 183
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • @Stargateur thanks! i had found that question but as the answer is pretty specific about `std::env::args()` at first i almost overlooked the helpful last part. so: yes, in a way the answer to my question is there but it is a bit hidden... – hiro protagonist Feb 18 '20 at 09:06

1 Answers1

2

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

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157