Skip to content

Instantly share code, notes, and snippets.

@TheCreatorAMA
Created August 19, 2022 14:57
Show Gist options
  • Select an option

  • Save TheCreatorAMA/ad3254a96ed2605eb64947d1fdc338ee to your computer and use it in GitHub Desktop.

Select an option

Save TheCreatorAMA/ad3254a96ed2605eb64947d1fdc338ee to your computer and use it in GitHub Desktop.
Rust convert string to pig latin(Rust lang book chapter 8 exercise)
fn main() {
let normal_str = String::from("first apple");
let pig_latin = convert_to_pig_latin(&normal_str);
println!("Input: {}\nOutput: {}", normal_str, pig_latin);
}
fn convert_to_pig_latin(input_str: &String) -> String {
let mut str_array = vec![];
// Splitting up words in input string
for word in input_str.to_lowercase().split_whitespace() {
// Init prefix and ending variables
let mut prefix = String::from("");
let mut ending = String::from("");
let mut count = 0;
// Loop through chars of each word. Counter is used to tell whether or not we are at the
// first char of a word, if so check if it is a vowel or not. If not on first char add
// chars to prefix.
for char in word.chars() {
match char {
'a' | 'e' | 'i' | 'o' | 'u' => {
if count == 0 {
ending.push_str("hay");
prefix.push(char);
} else {
prefix.push(char);
}
}
_ => {
if count == 0 {
ending.push_str(char.to_string().as_str());
ending.push_str("ay");
} else {
prefix.push(char);
}
}
}
count += 1;
}
// Join prefix and ending together to form new "pig latin" word. Push this new word to the
// array of strings
str_array.push(prefix + &"-".to_string() + &ending);
}
// Join array of pig latin strings together and return
str_array.join(" ")
}
@TheCreatorAMA
Copy link
Copy Markdown
Author

If you notice something would love some feedback!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment