Search code examples
stringutf-8rustiteratorslice

Creating a sliding window iterator of slices of chars from a String


I am looking for the best way to go from String to Windows<T> using the windows function provided for slices.

I understand how to use windows this way:

fn main() {
    let tst = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    let mut windows = tst.windows(3);

    // prints ['a', 'b', 'c']
    println!("{:?}", windows.next().unwrap());
    // prints ['b', 'c', 'd']
    println!("{:?}", windows.next().unwrap());
    // etc...
}

But I am a bit lost when working this problem:

fn main() {
    let tst = String::from("abcdefg");
    let inter = ? //somehow create slice of character from tst
    let mut windows = inter.windows(3);

    // prints ['a', 'b', 'c']
    println!("{:?}", windows.next().unwrap());
    // prints ['b', 'c', 'd']
    println!("{:?}", windows.next().unwrap());
    // etc...
}

Essentially, I am looking for how to convert a string into a char slice that I can use the window method with.


Solution

  • This solution will work for your purpose. (playground)

    fn main() {
        let tst = String::from("abcdefg");
        let inter = tst.chars().collect::<Vec<char>>();
        let mut windows = inter.windows(3);
    
        // prints ['a', 'b', 'c']
        println!("{:?}", windows.next().unwrap());
        // prints ['b', 'c', 'd']
        println!("{:?}", windows.next().unwrap());
        // etc...
        println!("{:?}", windows.next().unwrap());
    }
    

    String can iterate over its chars, but it's not a slice, so you have to collect it into a vec, which then coerces into a slice.