How do I replace specific characters idiomatically in Rust?

Also you can use iterators and match expression:

let s:String = "Hello, world!".chars()
    .map(|x| match x { 
        '!' => '?', 
        'A'..='Z' => 'X', 
        'a'..='z' => 'x',
        _ => x
    }).collect();
println!("{}", s);// Xxxxx, xxxxx?

You can replace all occurrences of one string within another with str::replace:

let result = str::replace("Hello World!", "!", "?");
// Equivalently:
result = "Hello World!".replace("!", "?");
println!("{}", result); // => "Hello World?"

For more complex cases, you can use regex::Regex::replace_all from regex:

use regex::Regex;
let re = Regex::new(r"[A-Za-z]").unwrap();
let result = re.replace_all("Hello World!", "x");
println!("{}", result); // => "xxxxx xxxxx!"

Tags:

Regex

Rust