Home
Rust
String replace Examples
This page was last reviewed on May 22, 2022.
Dot Net Perls
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 22, 2022 (image).
Home
Changes
© 2007-2024 Sam Allen.