I'm in the early stages of learning Rust and thought I'd do something a little more interesting based on the structure of the Guessing Game example from The Book. Everyone needs a program to help them write pangrams, right? (A pangram is a piece of text that contains every letter of the alphabet at least once. "The quick brown fox jumps over a lazy dog" is probably the best known example).
Anyway, I'm looking for any advice on how I can improve this, make it more idiomatic, more concise etc. A specific part I was wondering about was:
unused = unused[0..unused.len() - 2].to_string();
I'm sure there must be a more elegant way to remove the last two characters from a string. The only other thing I thought of was:
unused.pop();
unused.pop();
But again, it seems fairly inelegant just to repeat the same method call twice. I'm sure there are other parts of my code that could be better, too.
The full program is as follows:
use std::io;
fn main() {
println!("\nTry to type a pangram:");
loop {
let mut attempt = String::new();
io::stdin()
.read_line(&mut attempt)
.expect("Failed to read line");
attempt = attempt.trim().to_string();
let attempt_lc = attempt.to_lowercase();
if attempt_lc == "quit" {
println!("\nGoodbye.\n");
break;
}
let mut unused = String::new();
for char in 'a'..='z' {
if !attempt_lc.contains(char) {
unused.push(char);
unused.push_str(", ");
}
}
if unused == "" {
println!("\nWell done! \"{}\" is a pangram.\n", attempt);
println!("Try another one, or type \"quit\" to exit this program:");
} else {
unused = unused[0..unused.len() - 2].to_string();
println!("\nSorry, \"{}\" is not a pangram.", attempt);
println!("The following letters were not used:");
println!("{}\n", unused);
println!("Try again, or type \"quit\" to exit this program:");
}
}
}