Searching and replacing text

Rust:
Searching and replacing text

How to:

fn main() {
    let text = "Hello there!";
    let updated_text = text.replace("there", "world");
    println!("{}", updated_text); // Prints "Hello world!"
}

Sample output:

Hello world!

Deep Dive

Searching and replacing text has been around since early text editors emerged. Tools like sed in Unix made batch text processing common practice.

Rust takes an efficient, safe approach. The replace method, from the standard library’s str type, is straightforward and checks at compile-time.

Alternatives to replace include regex for complex patterns or iterating characters to customize replacement logic.

Under the hood, replace in Rust creates a new String, iterates through the original, finds matches, and then constructs the new string with replacements. It handles Unicode well, which isn’t trivial.

See Also