|
| 1 | +/* Task: |
| 2 | +Convert strings to pig latin. The first consonant of each word |
| 3 | +is moved to the end of the word and ay is added, so first becomes |
| 4 | +irst-fay. Words that start with a vowel have hay added to the end |
| 5 | +instead (apple becomes apple-hay). Keep in mind the details about |
| 6 | +UTF-8 encoding! |
| 7 | +*/ |
| 8 | + |
| 9 | +// =========================================================================== |
| 10 | + |
| 11 | +const VOWEL_CHARS: [char; 5] = ['a', 'o', 'u', 'e', 'i']; |
| 12 | + |
| 13 | +// =========================================================================== |
| 14 | + |
| 15 | +fn main() { |
| 16 | + // Tests |
| 17 | + assert_eq!(convert_word_to_pig_latin("Latin"), "atin-Lay"); |
| 18 | + assert_eq!(convert_word_to_pig_latin("Pig"), "ig-Pay"); |
| 19 | + assert_eq!(convert_word_to_pig_latin("Apple"), "Apple-hay"); |
| 20 | + |
| 21 | + assert_eq!(to_pig_latin("Pig Latin"), "ig-Pay atin-Lay"); |
| 22 | + assert_eq!( |
| 23 | + to_pig_latin("Apple Cookies Watermelon Avocado"), |
| 24 | + "Apple-hay ookies-Cay atermelon-Way Avocado-hay" |
| 25 | + ); |
| 26 | + // |
| 27 | +} |
| 28 | + |
| 29 | +fn convert_word_to_pig_latin(word: &str) -> String { |
| 30 | + let mut chars = word.chars(); |
| 31 | + |
| 32 | + match chars.next() { |
| 33 | + Some(c) if is_vowel(&c) => format!("{}-hay", word), |
| 34 | + Some(c) => format!("{}-{}ay", chars.as_str(), c), |
| 35 | + None => String::new(), |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +fn is_vowel(c: &char) -> bool { |
| 40 | + let lower_case_char: char = c.to_lowercase().next().unwrap(); |
| 41 | + VOWEL_CHARS.contains(&lower_case_char) |
| 42 | +} |
| 43 | + |
| 44 | +fn to_pig_latin(text: &str) -> String { |
| 45 | + let mut pigged = String::from(text); |
| 46 | + for i in text.split_whitespace() { |
| 47 | + pigged = pigged.replace(i, &convert_word_to_pig_latin(i)); |
| 48 | + } |
| 49 | + pigged |
| 50 | +} |
0 commit comments