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

To find the kth index of a character in a string in Rust, you can use the char_indices() method of the str type to get an iterator that returns each character and its corresponding index in the string. You can then use the nth() method of the iterator to get the element at the kth index.

Here's an example implementation:

main.rs
fn find_kth_index(string: &str, k: usize, character: char) -> Option<usize> {
    for (i, c) in string.char_indices() {
        if c == character {
            if i == k {
                return Some(i);
            }
        }
    }
    None
}
245 chars
11 lines

This function takes the input string, the index k, and the character you want to search for as parameters. It then loops over pairs of indices and characters in the string using char_indices(), checks if the character at the current index matches the character you're searching for, and if so, checks if the current index matches k. If there are no matches, the function returns None.

You can call this function like this:

main.rs
let s = "hello world";
let result = find_kth_index(s, 3, 'l');
assert_eq!(result, Some(3));
92 chars
4 lines

This will find the index of the third occurrence of the letter "l" in the string "hello world", which is 3.

gistlibby LogSnag