To find the index of the last occurrence of a substring in Rust, you can use the rfind
method of the String type.
In this example,
str
with a string value.rfind
method of the string type to find the index of the last occurrence of a specific character within str
.rfind
method returns the index of the last occurrence of the character in the string.fn main() {
let str = String::from("Hello World, Hello Rust");
let last_index = str.rfind('H').unwrap();
println!("Last index of substring is: {}", last_index);
}
Last index of substring is: 14
In this example,
str1
and str2
with different values.rfind
method of str1
to find the index of the last occurrence of str2
within str1
.rfind
method returns the index of the last occurrence of str2
in str1
.fn main() {
let str1 = String::from("apple banana cherry banana");
let str2 = "banana";
let last_index = str1.rfind(str2).unwrap();
println!("Last index of substring is: {}", last_index);
}
Last index of substring is: 17
In this tutorial, we learned How to find the Index of Last Occurrence of Substring in Rust language with well detailed examples.