.replace( ).replace( ).replace( ) , etc

Is there something like:

_my_string.replace(  { "\r\n", "\t" }   , " ") 

instead of:

.replace("\r\n", " ").replace("\t", " ").replace("..", " ").replace(......
1 Like

Not in the standard library AFAICT. Something like this should work:

use once_cell::sync::Lazy;

use aho_corasick::AhoCorasick;

static PATTERN: Lazy<AhoCorasick> = Lazy::new(|| AhoCorasick::new(["\r\n", "\t", ".."]));
static REPLACEMENTS: [&str; 3] = [" ", " ", " "];

pub fn demo(s: &str) -> String {
    PATTERN.replace_all(s, &REPLACEMENTS)
}

(playground)

4 Likes

Maybe this could do it?

my_string.replace(|c: char| c.is_control(), "");
1 Like

Also, it's possible to use replace_all_with to avoid allocating an array of replacements.

use once_cell::sync::Lazy;

use aho_corasick::AhoCorasick;

static PATTERN: Lazy<AhoCorasick> = Lazy::new(|| AhoCorasick::new(["\r\n", "\t", ".."]));

pub fn demo(s: &str) -> String {
    let mut dst = String::with_capacity(s.len());
    PATTERN.replace_all_with(s, &mut dst, |_, _, dst| {
        dst.push(' ');
        true
    });
    dst
}
6 Likes