Esercizi di Rust

Reverse a String in Rust

Reverse characters and words correctly, including letters like é.

  • Principiante
  • 2 min di lettura
  • 1 esempio eseguibile
Cosa imparerai
  • chars().rev()
  • collect into a String
  • Reversing words
reverse("Rust")
  1. 1chars()R u s t
  2. 2rev()t s u R
  3. 3collect()"tsuR"

Reverse characters, not bytes

Rust strings are UTF-8, so one character can take more than one byte. Reversing by characters with chars keeps letters such as é intact.

chars gives the characters one by one, rev reverses their order and collect builds a new String. split_whitespace does the same for words, and join puts them back together with spaces.

Punti chiave

  1. A character can take more than one byte.
  2. chars gives whole characters.
  3. collect builds the new String.

Esempio Rust eseguibile

Rust
Esegui il codice →
main.rs
fn reverse(text: &str) -> String {
    text.chars().rev().collect()
}

fn reverse_words(text: &str) -> String {
    text.split_whitespace().rev().collect::<Vec<&str>>().join(" ")
}

fn main() {
    println!("{}", reverse("Rust"));
    println!("{}", reverse("héllo"));
    println!("{}", reverse_words("safe fast productive"));
}
Crea un pulsante Run per questo esempio Risultato dell'esecuzione
tsuR
olléh
productive fast safe

Esercitati

Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.

Hai finito questa lezione?

Segnala come imparata per tenere traccia dei tuoi progressi.

Prossima: Tuples and Arrays →

Esercitati con una sfida

Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.

Tutte le sfide