Esercizi di Rust
Reverse a String in Rust
Reverse characters and words correctly, including letters like é.
Cosa imparerai
- chars().rev()
- collect into a String
- Reversing words
reverse("Rust")
- 1
chars()R u s t - 2
rev()t s u R - 3
collect()"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
- A character can take more than one byte.
- chars gives whole characters.
- collect builds the new String.
Esempio Rust eseguibile
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"));
}
tsuR
olléh
productive fast safeEsercitati
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.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
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