To find the index of a substring in Rust, you can use the find
method of the str
type.
In this example,
str
with a string value.find
method of str
to find the index of a specific substring within str
.find
method returns an Option
, which is Some(index)
if the substring is found, and None
otherwise.fn main() {
let str = "Hello World";
if let Some(index) = str.find("World") {
println!("Index of substring is: {}", index);
} else {
println!("Substring not found!");
}
}
Index of substring is: 6
In this example,
str1
and str2
with different values.find
method of str1
to find the index of str2
within str1
.find
method returns an Option
, which is Some(index)
if the substring is found, and None
otherwise.fn main() {
let str1 = "apple banana cherry banana";
let str2 = "cherry";
if let Some(index) = str1.find(str2) {
println!("Index of substring is: {}", index);
} else {
println!("Substring not found!");
}
}
Index of substring is: 13
In this tutorial, we learned How to find the Index of Substring in Rust language with well detailed examples.