/*
Find all starting indices of a word inside a larger text.
This function uses the built‑in find method on &str, which returns
an Option<usize> indicating the next match. We loop until no more
matches exist.
*/
fn find_all_occurrences(text: &str, word: &str) -> Vec<usize> {
let mut indices: Vec<usize> = Vec::new();
// Searching for an empty word is meaningless
if word.is_empty() {
return indices;
}
let mut start: usize = 0;
/*
Loop:
- Search for the word starting at `start`.
- If found, record the index.
- Move forward by one character to allow overlapping matches.
*/
while let Some(pos) = text[start..].find(word) {
let absolute_index = start + pos;
indices.push(absolute_index);
start = absolute_index + 1;
}
indices
}
fn main() {
let text: &str =
"the quick brown fox jumps over the lazy dog. the fox is clever.";
let word: &str = "the";
println!("Text: {}", text);
println!("Word: \"{}\"\n", word);
println!("Occurrences at indices:");
for idx in find_all_occurrences(text, word) {
println!("{}", idx);
}
}
/*
run:
Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"
Occurrences at indices:
0
31
45
*/