In Rust, we can replace the content of a string with the replace()
method. This method replaces a specified match with another string.
string.replace(match, substring)
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.
This method returns a new string with every match replaced. If no match is found, the string remains the same.
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"));}
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.
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