Rust Practice Exercises
Palindrome Check in Rust
Does the text read the same in both directions? Ignore spaces, punctuation and case.
What you'll learn
- Filtering letters
- Lower case
- Comparing with the reverse
level
l0
e1
v2
e3
l4
The same forwards and backwards
A palindrome reads the same in both directions, such as level. A good check ignores spaces, punctuation and the difference between upper and lower case.
filter keeps only letters and digits and map makes them lower case. eq compares the letters with the same letters in reverse order, without building a second vector. {text:?} prints the text with quotes.
Key points
- Keep only letters and digits.
- Compare in lower case.
- eq compares two iterators item by item.
Runnable Rust example
Rust
main.rs
fn is_palindrome(text: &str) -> bool {
let letters: Vec<char> = text
.chars()
.filter(|c| c.is_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
letters.iter().eq(letters.iter().rev())
}
fn main() {
for text in ["level", "A man, a plan, a canal: Panama", "Rust"] {
println!("{text:?} -> {}", is_palindrome(text));
}
}
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Rust" -> falsePractice
Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.
Finished this lesson?
Mark it as learned to track your progress.
Your progress is saved in this browser Sign in to keep it on every device.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Palindrome String Check whether text reads the same forwards and backwards. Easy
- Palindrome Number Check whether a number reads the same backwards. Easy