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}");
}
Replacing text in a string in Rust creates a brand new string with the old text swapped out for new text, leaving the original string untouched. Think of it like photocopying a document, editing the copy, and keeping the original safe. You use this whenever you need to correct or update text without altering the source data.