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.
Replace()
copies the string
and returns a modified copy. We specify 2 arguments to replace: the "before" slice, and the "after" slice.
When we call replace, we pass it 2 string
literals. Here we change a 2-letter string
slice into the characters "alf."
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
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?
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."
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 replaceThe 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.
char
argument (a space) in the replace function call. It removes all spaces from the string
.string
as the first argument to replace()
.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
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.