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)
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 matchesprintln!("{}", 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
betteris replaced bybestat every occurrence.For second example:
boringis replaced byinteresting.For the third and fourth examples: there wasn’t any match so the string is returned as it was.
Free Resources