In Rust, you can find the index of a substring using str::find():
s.find(sub) // returns Some(index) of first occurrence, or None if not found
s.rfind(sub) // returns Some(index) of last occurrence
s[start..].find(sub) // search starting from index `start`
Here are some examples:
let sentence = "Hello World";
let idx = sentence.find("World");
println!("{:?}", idx); // Some(6)
if sentence.find("xyz").is_none() {
println!("not found");
}
The index returned is the position of the first character of the found substring. Returns None if not found.
Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!
Hint
Use sentence.find("World") and assign the result to idx.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check