snippetrustCritical
How do I replace specific characters idiomatically in Rust?
Viewed 0 times
replacehowidiomaticallycharactersrustspecific
Problem
So I have the string "Hello World!" and want to replace the "!" with "?" so that the new string is "Hello World?"
In Ruby we can do this easily with the
How to do this idiomatically in Rust?
In Ruby we can do this easily with the
gsub method:"Hello World!".gsub("!", "?")
How to do this idiomatically in Rust?
Solution
You can replace all occurrences of one string within another with
For more complex cases, you can use
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!"Code Snippets
let result = str::replace("Hello World!", "!", "?");
// Equivalently:
result = "Hello World!".replace("!", "?");
println!("{}", result); // => "Hello World?"use regex::Regex;
let re = Regex::new(r"[A-Za-z]").unwrap();
let result = re.replace_all("Hello World!", "x");
println!("{}", result); // => "xxxxx xxxxx!"Context
Stack Overflow Q#34606043, score: 162
Revisions (0)
No revisions yet.