Rust Practice Exercises

Palindrome Check in Rust

Does the text read the same in both directions? Ignore spaces, punctuation and case.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • Filtering letters
  • Lower case
  • Comparing with the reverse
level
l0
e1
v2
e3
l4
The first and last letters match, then the next pair.

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

  1. Keep only letters and digits.
  2. Compare in lower case.
  3. eq compares two iterators item by item.

Runnable Rust example

Rust
Run code →
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));
    }
}
Get a Run button for this example Result of running the code
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Rust" -> false

Practice

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.

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.

All challenges