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
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
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