Start learning free

LESSON 67 OF 679 · STRINGS I

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