How do I insert values between each element of a list?

Viewed 346

This (playground):

let s = "Hello world!";
let splitted_string = s.split_terminator("").skip(1).collect::<Vec<&str>>();
println!("splitted_string: {:?}", splitted_string);

results in the following output:

splitted_string: ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

How can I insert an a between each element and obtain something like this?

["H", "a", "e", "a", "l", "a", "l", "a", "o", "a", " ", "a", "w", "a", "o", "a", "r", "a", "l", "a", "d", "a", "!"]
2 Answers

It is still experimental, but iter::intersperse does exactly that.

From the doc example:

#![feature(iter_intersperse)]

let mut a = [0, 1, 2].iter().intersperse(&100);
assert_eq!(a.next(), Some(&0));   // The first element from `a`.
assert_eq!(a.next(), Some(&100)); // The separator.
assert_eq!(a.next(), Some(&1));   // The next element from `a`.
assert_eq!(a.next(), Some(&100)); // The separator.
assert_eq!(a.next(), Some(&2));   // The last element from `a`.
assert_eq!(a.next(), None);

In the meanwhile, the itertools::intersperse crate has the same functionality.

A solution that only uses the current stable standard library:

use std::iter;
fn main() {
    let s = "Hello world!";
    let result: Vec<char> = s
        .chars()
        .zip(iter::repeat('a'))
        .flat_map(|(a, sep)| vec![sep, a])
        .skip(1)
        .collect();
    println!("{:?}", result);
}

Results:

['H', 'a', 'e', 'a', 'l', 'a', 'l', 'a', 'o', 'a', ' ', 'a', 'w', 'a', 'o', 'a', 'r', 'a', 'l', 'a', 'd', 'a', '!']

Playground

There's already a good .flat_map() answer, but to give a slightly different approach for the sake of variety, we can shave that extra 'a' off the end by using .take():

fn main() {
    let s = "Hello world!";
    
    let interspersed = s.chars()
                        .flat_map(|c| [c, 'a'])
                        .take(s.len() * 2 - 1)
                        .collect::<String>();
                        
    println!("interspersed: {:?}", interspersed);
}

output:

interspersed: "Haealalaoa awaoaralada!"
Related