This is the code I came up with for the Rust pig latin exercise.
I am looking for suggestions on how to make it more idiomatic.
I think working with iterators instead of chars and Strings would be a step in the right direction?
I was unable to figure out how to use .map
to reach the same result. I would have liked to iterate over a SplitWhiteSpace
and apply the manipulations to each slices in one pass instead of using a for loop
.
fn main() {
let phrase = "Test sentence for pig latin f 🎈🎆🎇 नर र स्का स्कास्का 🧨".to_lowercase();
let split = phrase.split_whitespace();
let mut pigifyed: String = String::new();
for word in split {
let mut chars = word.chars();
let firstchar = chars.next().unwrap();
if chars.next() == None {
pigifyed = format!("{} {}ay", pigifyed, firstchar)
} else if is_vowel(&firstchar) {
pigifyed = format!("{} {}-hay", pigifyed, word);
} else {
let end = &word[firstchar.len_utf8()..];
pigifyed = format!("{} {}-{}ay", pigifyed, end, firstchar);
}
}
println!("{}", pigifyed)
}
fn is_vowel(char: &char) -> bool {
let vowels = ['a', 'e', 'i', 'o', 'u'];
vowels.contains(char)
}
Output:
est-tay entence-say or-fay ig-pay atin-lay fay 🎆🎇-🎈ay र-नay रay ्का-सay ्कास्का-सay 🧨ay