find the kth index of a substring in a string in rust

To find the kth index of a substring in a string in Rust, we can use the find method along with a for loop to iterate k times until we find the desired occurrence.

Here's an example code snippet:

main.rs
fn find_kth_index(text: &str, substr: &str, k: usize) -> Option<usize> {
    let mut index = text.find(substr)?;
    for _ in 1..k {
        index = text[index + substr.len()..].find(substr)?;
        index += substr.len();
    }
    Some(index)
}
248 chars
9 lines

This function takes in three parameters - text which is the string to search in, substr which is the substring to search for, and k which is the index of the occurrence of the substring we want to find.

The find method returns an Option<usize> which is None if the substring is not found or Some(index) if it is found. We store the first occurrence of the substring in the index variable.

Then, we use a for loop to iterate k times. In each iteration, we find the next occurrence of the substring in the remaining part of the text after the previous occurrence. We then add the length of the substring to the found index and store it in the index variable for the next iteration.

Finally, we return the Some(index) value wrapped in an Option, which is the kth index of the substring in the text. If the substring is not found, None is returned.

gistlibby LogSnag