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

To find the last index of a character in a string in Rust, you can use the rfind method of the str type. This method returns an Option<usize> which is the index of the last occurrence of the searched substring.

Here is an example code snippet:

main.rs
let my_string = "hello, world";
let my_char: char = 'o';

let last_index = my_string.rfind(my_char);

match last_index {
    Some(idx) => println!("The last index of {} is {}", my_char, idx),
    None => println!("{} not found in '{}'", my_char, my_string)
}
259 chars
10 lines

In this example, the my_string variable stores the string "hello, world" and my_char stores the character 'o'. The rfind method is called on my_string with my_char as its argument. The return value is stored in last_index.

A match block is used to check if the last_index is Some or None. If it is Some, then the last index of the provided character is printed using println! macro. Otherwise, a message indicating that the character was not found in the string is printed.

Note that the rfind method returns the last index of a character with respect to the left-to-right iteration over the string. If you need the last index with respect to the right-to-left iteration, you can use the find method instead.

gistlibby LogSnag