Find The Last Occurrence Of A Character In A String In Rust
Code snippet for how to Find The Last Occurrence Of A Character In A String In Rust with sample and detail explanation
Determining the position of the last occurrence of a specific character in a string is a common task in programming. In this short article, we will look at how to accomplish this in the Rust language.
Code snippet - Finding the last occurrence of a character in a string
fn find_last(s: &str, c: char) -> Option<usize> {
s.char_indices().rfind(|&(_, x)| x == c).map(|(i, _)| i)
}
fn main() {
let text = "hello";
find_last(&text, 'l').map(|pos| println!("{}", pos));
// This will print 3
}
Code Explanation - Finding the last occurrence of a character in a string
In the above code snippet, we start with declaring a function find_last(s: &str, c: char) -> Option<usize>
, which returns the last index of a given character in a string.
First, we are using the char_indices()
function which gives us an iterator over (index, char)
pairs. So, we enumerate each character of the string along with its index.
The rfind
function is then used to find the last element (i.e., the last pair of (index, char)
) that satisfies a certain condition. In this case, we are checking for the last pair where the character matches our specified character. This will return Some((i, c))
where i
is the index and c
is the character, or None
if no matching character is found.
Next, we use map(|(i, _)| i)
to turn Some((i, c))
into Some(i)
, essentially stripping off the character and retaining the index only. If no match was found (if rfind
returned None
) then map
does nothing and None
is returned by the function.
Finally, in the main
function, we call the find_last
function with the text 'hello'
and the character l
. The map
on the result is used to print the position if a match was found.
This rust function provides an efficient and simple way to find the last occurrence of a character in a string in Rust.