Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding index of slice idiomatically (needle in the haystack)

Javascript provides
"abcde".indexOf("de") === 3.

I’d like to do the same thing for a &[T] where T implements PartialEq.

fn search_haystack<T: PartialEq>(needle: &[T], haystack: &[T]) -> Option<usize> {
    todo!()
}
fn main() {
    let haystack = [1,2,3,4,5];
    let needle = [3,4];
    assert_eq!(search_haystack(&needle, &haystack), Some(2))
}

I could write this function myself but it seems like something the stdlib would offer, and I have not been able to find it. How do I accomplish this efficiently using the stdlib (not nightly).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use slice.windows(n) to get an iterator of all subslices of length n. You can combine that with iterator.position() to find the first subslice that is equal to needle:

fn search_haystack<T: PartialEq>(needle: &[T], haystack: &[T]) -> Option<usize> {
    if needle.is_empty() {
        // special case: `haystack.windows(0)` will panic, so this case
        // needs to be handled separately in whatever way you feel is
        // appropriate
        return Some(0);
    }

    haystack.windows(needle.len()).position(|subslice| subslice == needle)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading