I've started learning Rust a few days ago. This is the Pig Latin exercise from the Rust Book. The code works as expected. I have commented the logic of the program in the code.
My handling of String
s is very hacky, as far as I know. To be honest, I mostly fiddled with it looking at error messages until the compiler was satisfied. I'd like to know what would be a idiomatic and may be more readable way to write it and if there as sane ways to optimize, especially the string manipulation part.
Thank you
use std::io;
fn main() {
println!("Please enter a sentence:");
const VOWELS: &str = "aeoiu";
let mut sentence = String::new();
io::stdin()
.read_line(&mut sentence)
.expect("An error occured");
let mut words = sentence
.split_whitespace()
.map(|x| String::from(x))
.collect::<Vec<String>>();
for word in &mut words {
if VOWELS.contains(word.chars().nth(0).unwrap().to_ascii_lowercase()) {
// Starts with consonant:
// The first consonant of each word is moved to the end of the word
// and “ay” is added, so “first” becomes “irst-fay.”
*word = format!("{}-hay", (*word).clone());
// *word = (*word).clone() + "-" + "hay";
} else {
// Starts with a vowel:
// Add “hay” to the end (“apple” becomes “apple-hay”).
*word = format!(
"{}-{}ay",
String::from(&word[1..]),
word.chars().nth(0).unwrap().to_string()
);
// String::from(&word[1..]) + "-" + &(word.chars().nth(0).unwrap().to_string()) + "ay";
}
}
println!("{}", words.join(" "))
```