'How to find the last occurrence of a char in a string?

I want to find the index of the last forward slash / in a string. For example, I have the string /test1/test2/test3 and I want to find the location of the slash before test3. How can I achieve this?

In Python, I would use rfind but I can't find anything like that in Rust.



Solution 1:[1]

@ljedrz's solution will not give you the correct result if your string contains non-ASCII characters.

Here is a slower solution but it will always give you correct answer:

let s = "/test1/test2/test3";
let pos = s.chars().count() - s.chars().rev().position(|c| c == '/').unwrap() - 1;

Or you can use this as a function:

fn rfind_utf8(s: &str, chr: char) -> Option<usize> {
    if let Some(rev_pos) = s.chars().rev().position(|c| c == chr) {
        Some(s.chars().count() - rev_pos - 1)
    } else {
        None
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OverShifted