Home
Search
Rust Replace String ExamplesReplace string parts with other string parts in programs. Understand the details of string replacement.
Replace. Strings must be often changed—or more accurately, modified copies must be made of them. In Rust, like most other languages, we can replace() strings.
Function notes. Replace() copies the string and returns a modified copy. We specify 2 arguments to replace: the "before" slice, and the "after" slice.
Simple example. When we call replace, we pass it 2 string literals. Here we change a 2-letter string slice into the characters "alf."
And We end up with the word "calf" instead of the word "cat." At least we are still dealing with an animal.
fn main() { let animal = "cat"; // Replace a string-slice with another in the string. // ... A new string is returned. let result = animal.replace("at", "alf"); println!("REPLACED: {}", result); }
REPLACED: calf
All instances. An important thing to keep in mind with the Rust replace() function is that it acts upon every instance. So if the letters "bc" occur twice, they are all modified.
fn main() { let source = "abcabc"; // All matches found by replace() are affected. println!("ALL MATCHES: {0}", source.replace("bc", "?")); }
ALL MATCHES: a?a?
Replacen example. If we only want to replace the first matching instance of a pattern, we can use replacen. Pass the argument 1 to indicate "first only."
Tip Other numbers will also have the expected result—for example, 2 will modify 2 matches only.
fn main() { let source = "ABCABC"; // Use replacen and specify 1 as the third argument. // ... This replaces only the first match. let replace_first = source.replacen("BC", "_", 1); println!("FIRST MATCH ONLY: {0}", replace_first); }
FIRST MATCH ONLY: A_ABC
Char argument replace. The clippy tool warns us when we try to call replace() with a single-character string as the first argument. A char can be used if a single character is being replaced.
Version 1 This code uses a char argument (a space) in the replace function call. It removes all spaces from the string.
Version 2 This version of the code does the same thing as version 1, but uses a 1-char string as the first argument to replace().
Result Clippy is correct in its advice—using a char argument is measurably and consistently faster than using a 1-char string.
use std::time::*; fn main() { if let Ok(max) = "10000000".parse() { // Version 1: use char replace function. let t0 = Instant::now(); let mut count1 = 0; for _ in 0..max { let x = "cat is cute and soft".to_string(); let result = x.replace(' ', ""); count1 += result.len(); } println!("{}", t0.elapsed().as_millis()); // Version 2: use string replace function. let t1 = Instant::now(); let mut count2 = 0; for _ in 0..max { let x = "cat is cute and soft".to_string(); let result = x.replace(" ", ""); count2 += result.len(); } println!("{}", t1.elapsed().as_millis()); println!("{}/{}", count1, count2); } }
947 ms (char) 994 ms 160000000/160000000
A summary. When dealing with strings in Rust, replacements are usually not far away. Replace() helps, and it tends to follow the rules of other languages—it has few quirks.
Home
© 2007-2022 sam allen.
see site info on the changelog.