To find the indices of all occurrences of a substring in Rust, you can use the find_indices method of the str type to find all occurrences and store their indices.
In this example,
str
with a string value.find_indices
method of the str
type with the substring to find all occurrences and store their indices.fn main() {
let str = "Hello Hello Hello";
let substr = "Hello";
let indices: Vec<usize> = str.match_indices(substr).map(|(idx, _)| idx).collect();
println!("Indices of all occurrences: {:?}", indices);
}
Indices of all occurrences: [0, 6, 12]
In this example,
str
and substr
with different values.find_indices
method of the str
type with the substring to find all occurrences and store their indices.fn main() {
let str = "apple banana cherry banana";
let substr = "banana";
let indices: Vec<usize> = str.match_indices(substr).map(|(idx, _)| idx).collect();
println!("Indices of all occurrences: {:?}", indices);
}
Indices of all occurrences: [6, 20]
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in Rust language with well detailed examples.