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.
You need to use std::str::rfind
. Note that it returns an Option<usize>
, so you will need to account for that when checking its result:
fn main() {
let s = "/test1/test2/test3";
let pos = s.rfind('/');
println!("{:?}", pos); // prints "Some(12)"
}
@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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With