Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 600
bmartin Avatar asked Jul 10 '18 04:07

bmartin


1 Answers

You can use itertools to walk over windows of any iterator, up to a width of 4:

extern crate itertools; // 0.7.8

use itertools::Itertools;

fn main() {
    let input = "日本語";

    for (a, b) in input.chars().tuple_windows() {
        println!("{}, {}", a, b);
    }
}

See also:

  • Are there equivalents to slice::chunks/windows for iterators to loop over pairs, triplets etc?
like image 61
Shepmaster Avatar answered Oct 24 '22 17:10

Shepmaster