How to replace substring in Rust

Use the replace method on a String to create a new string with the specified substring swapped out.

Use the replace method on a String to create a new string with the substring swapped out, as strings are immutable by default.

let original = String::from("hello world");
let replaced = original.replace("world", "Rust");
println!("{replaced}"); // hello Rust

If you need to modify the original string in place, call replace and reassign the result back to the variable.