Start learning free

LESSON 65 OF 348 · STRINGS I

String Find in Rust in Rust

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check

    String Find in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free