How to Replace Text in a String in Rust

Use the replace method on a String to generate a new string with the specified text substituted.

Use the replace method on a String to create a new string with all occurrences of a substring replaced. Because String is immutable by default, you must assign the result to a new variable or a mutable one.

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