Another problem today, don’t worry I’ll get back to theoretical stuff next time. Today we are removing vowels from words in other words we are Disemvoweling a string. I love that word.
Example
“Hello World!” => “Hll Wrls!”
Disemvowel Solution
If this was Javascript I’d use a regex to seek and destroy all vowels and call it a night… So let’s do that in Rust.
use regex::Regex;
fn disemvowel(s: &str) -> String {
let re = Regex::new(r"(?i)[aeiou]").unwrap();
let result = re.replace_all(s, "");
result.to_string()
}
Code language: Rust (rust)
It took me a second to figure out how to regex
in rust. But when I did the solution came out as simple as it would in JavaScript. A bit more verbose but simple nonetheless.
The idea is to make a regex that searches for the 5 vowels ignoring the case, then use that expression to replace every matching character in the input string.
In JavaScript I could get it down to one readable line;
function disemvowel(str) {
return str.replace(/[aeiou]/ig, '');
}
Code language: JavaScript (javascript)
The part that confused me a bit was the (?i)
since I did not know how to specify that at first. But a second in the docs for the regex crate and I got that to work.
I’m also not sure what the deal with unwrap()
is, but I’m sure there is a good reason. All in all, it was a nice learning experience. How would you solve this problem in Rust, JavaScript, or whatever language you use to code? Let me know on Twitter, @phoexer and as always happy coding.