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

To find the last index of a substring in a string in Rust, you can use the rfind method of the str type. Here is an example:

main.rs
let my_string = "hello world";
let my_substring = "world";
let last_index = my_string.rfind(my_substring).unwrap();
println!("Last index of {}: {}", my_substring, last_index);
176 chars
5 lines

In this example:

  • my_string is the string in which we want to find the last index of a substring.
  • my_substring is the substring we want to find the last index of.
  • rfind is the method that finds the last index of my_substring in my_string.
  • unwrap is used to extract the index from the Option<usize> returned by rfind. If rfind returns None, unwrap will panic.

The output of this code will be:

main.rs
Last index of world: 6
23 chars
2 lines

In this case, the last index of "world" in "hello world" is 6.

gistlibby LogSnag