What is the string.replace() method in Rust?

Overview

In Rust, we can replace the content of a string with the replace() method. This method replaces a specified match with another string.

Syntax

string.replace(match, substring)
Syntax for replace() method in Rust

Parameters

  • string: This is the string whose substring we want to replace.

  • match: This is the match we want to find and replace.

  • substring: This is the replacement for the match we find.

Return value

This method returns a new string with every match replaced. If no match is found, the string remains the same.

Code example

fn main() {
let str1 = "Edpresso is better than Rust but Rust is better than C++";
let str2 = "Rust is boring!";
let str3 = "I love coding";
let str4 = "Match me!";
// Replacing some matches
println!("{}", str1.replace("better", "best"));
println!("{}", str2.replace("boring", "interesting!"));
println!("{}", str3.replace("Me", "You"));
println!("{}", str4.replace("Find", "Match"));
}

Explanation

  • Lines 2–5: We create some strings.

  • Lines 8–11: We replace some sub-strings of the strings we created using the replace() method. Then, we print the results to the console.

Output

  • For first example: the word better is replaced by best at every occurrence.

  • For second example: boring is replaced by interesting.

  • For the third and fourth examples: there wasn’t any match so the string is returned as it was.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved