Solution to second exercise from chapter 8

exercise from chapter 8:

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”). Keep in mind the details about UTF-8 encoding!

Here's the final version of my solution. If you have any suggestions for making it more idiomatic or efficient, please let me know. Thank you in advance!

const VOWELS: &str = "AEIOUaeiou";

fn to_list(text: &str) -> Vec<&str> {
    let mut result = Vec::new();
    let mut last = 0;
    for (index, matched) in text.match_indices(|c: char| !(c.is_alphanumeric())) {
        if last != index {
            result.push(&text[last..index]);
        }
        result.push(matched);
        last = index + matched.len();
    }
    if last < text.len() {
        result.push(&text[last..]);
    }
    result
}

fn to_pig(word: &str) -> String {
    match word.chars().all(|ch| ch.is_alphabetic()) {
        true => {
            if VOWELS.contains(&word[0..1]) {
                format!("{}-hay", word)
            } else {
                let ch = word.chars().next().unwrap().to_lowercase();
                format!("{}-{}ay", &word[1..], ch)
            }
        }
        false => format!("{}", word),
    }
}

fn main() {
    let string = "I think; I gOT, it. ::'figured' out!!!🔥✅🔥";
    
    let text_list = to_list(&string);
    let mut pig = Vec::new();
    for word in text_list {
        pig.push(to_pig(word));
    }

    // println!("{:?}", pig);
    println!("{}", pig.join(""));
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.