Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

Rust str::replace and replacen

Reference for Rust str::replace, replacen and replace_range: patterns, replacement counts, allocation, and why replacing never edits a &str in place.

str::replace returns a new String in which every match of a pattern is replaced by another string. replacen does the same but stops after a given number of replacements. Because a &str is immutable and the result may have a different length, these methods always allocate a new string; the original is untouched.

To change a range of an existing String in place, use String::replace_range, which takes byte offsets instead of a pattern.

Rust
let fixed = "colour".replace("ou", "o");
assert_eq!(fixed, "color");

Try it

Rust Replacing text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Edge cases and replace_range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn replace<P: Pattern>(&self, from: P, to: &str) -> String
fn replacen<P: Pattern>(&self, pat: P, to: &str, count: usize) -> String
fn replace_range<R: RangeBounds<usize>>(&mut self, range: R, replace_with: &str)
Name Description
from, pat What to find: char, &str, char array/slice or char closure.
to The replacement text, inserted literally. It must be a &str, not a char.
count The maximum number of replacements. 0 means none.
range Byte range of the String to overwrite.

Returns: replace and replacen return a new String. replace_range returns nothing.

Errors / panics / edge cases: replace_range panics if the range start or end is not on a character boundary or is out of bounds. replace and replacen never panic.

Usage notes

  • The replacement is a &str. "abc".replace('b', 'x') does not compile; write "x" or &'x'.to_string().
  • Matches are found left to right and do not overlap. The replaced text is not searched again, so "a".replace("a", "aa") is "aa", not an endless loop.
  • No patterns of the regex kind. Replacing with capture groups needs a crate; in std combine find, slicing and push_str.
  • Order matters when chaining. Escape & first when also escaping <, as in the example, or you would double-escape.
  • Always allocates, even if nothing matches. If you only want to change text when needed, test contains first, or use Cow<str>.
  • ASCII-only changes can use replace safely; for case changes see to_uppercase and to_lowercase.
  • Cost: linear in the length of the text, plus one allocation for the output.