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

后端 未结 3 1231
失恋的感觉
失恋的感觉 2021-01-17 23:57

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

I understa

3条回答
  •  既然无缘
    2021-01-18 00:53

    This solution will work for your purpose. (playground)

    fn main() {
        let tst = String::from("abcdefg");
        let inter = tst.chars().collect::>();
        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.

提交回复
热议问题