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

Overview

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.

Syntax

string.replacen(match, substring, n)
Syntax of the replacen() method in Rust

Parameters

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

Return value

The replacen() method returns a new string in which all the specified and found matches have been replaced.

Example

fn main() {
// create some strings
let 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 matches
println!("{}", str1.replacen("me", "myself", 2)); // replace first two "me"s
println!("{}", str2.replacen("Java", "JavaScript", 1)); // replace first one "Java"
println!("{}", str3.replacen("bar", "baz", 3)); // replace first three "foo"s
}

Explanation

  • Lines 3–5: We declare and initialize three strings: str1, str2, and str3.
  • Lines 8–10: We use the replacen() method to replace the specified matches found in the respective strings, and print the results to the console.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources