Start learning free

LESSON 66 OF 348 · STRINGS I

String Replace in Rust in Rust

Lesson

In Rust, the .replace() method replaces every occurrence of a substring with a new string. It takes the substring to find and the replacement directly:

let result = sentence.replace("cats", "dogs");
// .replace() takes the substring to find
// "dogs" is the replacement

Here is an example:

let sentence = "I love cats";
let result = sentence.replace("cats", "dogs");
println!("{}", result);  // "I love dogs"

Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!


Hint
Use sentence.replace("cats", "dogs") and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    String Replace 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