Exercícios de Rust

Palindrome Check in Rust

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

  • Iniciante
  • 2 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • 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.

Pontos-chave

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

Exemplo executável de Rust

Rust
Executar código →
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));
    }
}
Gerar um botão Run para este exemplo Resultado da execução
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Rust" -> false

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Próxima: Word Frequency Counter →

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios