Created
August 19, 2022 14:57
-
-
Save TheCreatorAMA/ad3254a96ed2605eb64947d1fdc338ee to your computer and use it in GitHub Desktop.
Rust convert string to pig latin(Rust lang book chapter 8 exercise)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(" ") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you notice something would love some feedback!