diff options
Diffstat (limited to '')
| -rw-r--r-- | src/piglatin/Cargo.toml | 6 | ||||
| -rw-r--r-- | src/piglatin/src/main.rs | 67 |
2 files changed, 73 insertions, 0 deletions
diff --git a/src/piglatin/Cargo.toml b/src/piglatin/Cargo.toml new file mode 100644 index 0000000..725b8b5 --- /dev/null +++ b/src/piglatin/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "piglatin" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/piglatin/src/main.rs b/src/piglatin/src/main.rs new file mode 100644 index 0000000..c993c52 --- /dev/null +++ b/src/piglatin/src/main.rs @@ -0,0 +1,67 @@ +/* + * Chapter: + * 8.3 Storing Keys with assosiated Values in Hash Maps + * + * Link: + * https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#summary + * + * Task: + * 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! + * + * Example input/output: + * I: "pig" + * O: "igpay" + * + * I: "latin" + * O: "atinlay" + * + * I: "banana" + * O: "ananabay" + * + */ + +fn main() { + println!("{}", str2pig_latin("1bcdege")); + println!("{}", str2pig_latin("pig")); + println!("{}", str2pig_latin("world")); + println!("{}", str2pig_latin("world of warcraft")); +} + +fn str2pig_latin(input: &str) -> String { + let mut output = String::new(); + + for word in input.split_whitespace() { + if !output.is_empty() { + output.push(' '); + } + + let end_byte = word + .char_indices() + .find(|&(_, c)| !is_consonant(c)) + .map_or(word.len(), |(i, _)| i); + + let (head, tail) = word.split_at(end_byte); + + if head.is_empty() { + output.push_str(word); + output.push_str("-hay"); + } else { + output.push_str(tail); + output.push_str(head); + output.push_str("ay"); + } + } + + output +} + +fn is_vowel(c: char) -> bool { + matches!(c.to_ascii_lowercase(), 'a' | 'e' | 'i' | 'o' | 'u') +} + +fn is_consonant(c: char) -> bool { + c.is_ascii_alphabetic() && !is_vowel(c) +} |
