You can do this with a String
using contains
which searches for a pattern, but Vec::contains
is for a single element.
The only way I've been able to do this is by directly implementing some kind of substring function, but I'm sort of hoping there's a built-in way.
let vec1 = vec![1, 2, 3, 4, 5];
let vec2 = vec![2, 3]; // vec2 IS a substring of vec1
let vec3 = vec![1, 5]; // vec3 is NOT a substring of vec3
fn is_subvec(mainvec: &Vec<i32>, subvec: &Vec<i32>) -> bool {
if subvec.len() == 0 { return true; }
if mainvec.len() == 0 { return false; }
'outer: for i in 0..mainvec.len() {
for j in 0..subvec.len() {
if mainvec[i+j] != subvec[j] {
continue 'outer;
}
}
return true;
}
return false;
}
println!("should be true: {}", is_subvec(&vec1, &vec2));
println!("should be false: {}", is_subvec(&vec1, &vec3));
I've seen How can I find a subsequence in a &[u8] slice?, but that's specifically for u8
and I want something that applies regardless of the type in the Vec
.