std-method

str::replace

Build a new String with matching portions replaced. The source remains available. Expected stdout (not executed): green,green,blue Common mistake: Expecting replace to modify its receiver in place.

Formal Syntax & Structure

rust syntaxrust
fn replace<P: Pattern>(&self, from: P, to: &str) -> String

Working Example

Example Snippetrust
fn main() {    let text = "red,red,blue";    let result = text.replace("red", "green");    println!("{result}");}
Rust Reference