I'm learning Rust and one of the challenges in the book was to build a pig latin translator.
Convert strings to pig latin. The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”).
I came up with the code below and I'm looking for ways to improve it, specifically reducing the push_str
s and improving the starts_with_a_vowel
method. How can the code be improved?
main.rs
extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;
fn main() {
println!("{}", pig_latinify("String me".to_string()));
}
fn transform_word(word: &str) -> String {
let mut new_word = String::new();
new_word.push_str(&word[1..]);
new_word.push_str(&word[..1]);
if starts_with_a_vowel(word) {
new_word.push_str("h");
}
new_word.push_str("ay");
new_word
}
fn starts_with_a_vowel(word: &str) -> bool {
let vowels = ["a", "e", "i", "o", "u"];
for vowel in &vowels {
if word.starts_with(vowel) {
return true;
}
}
false
}
fn pig_latinify(statement: String) -> String {
let mut transformed_statement = String::new();
if !statement.is_ascii() {
panic!("statement must be ascii");
}
let iter = statement.split_word_bounds();
for word in iter {
if word.trim().len() > 0 {
transformed_statement.push_str(&transform_word(word));
transformed_statement.push_str(" ");
}
}
transformed_statement.trim();
transformed_statement
}
Cargo.toml
...
[dependencies]
unicode-segmentation = "1.2.0"