The replacen()
method replaces the first n matches of a substring in a string. If we specify a match and several matches are found, we can specify the number of matches to replace.
string.replacen(match, substring, n)
match
: This is the match we want to find and replace.
substring
: This is the replacement for the match if it's found.
n
: This represents the first n number of matches to replace in string
. .
The replacen()
method returns a new string in which all the specified and found matches have been replaced.
fn main() {// create some stringslet str1 = "me you me I we me";let str2 = "Rust Java Java Rust Rust";let str3 = "foo bar bar bar bar foo bar bar";// replace some matchesprintln!("{}", str1.replacen("me", "myself", 2)); // replace first two "me"sprintln!("{}", str2.replacen("Java", "JavaScript", 1)); // replace first one "Java"println!("{}", str3.replacen("bar", "baz", 3)); // replace first three "foo"s}
str1
, str2
, and str3
.replacen()
method to replace the specified matches found in the respective strings, and print the results to the console.