Rust Practice Exercises
Reverse a String in Rust
Reverse characters and words correctly, including letters like é.
What you'll learn
- 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.
Key points
- A character can take more than one byte.
- chars gives whole characters.
- collect builds the new String.
Runnable Rust example
Rust
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 safePractice
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.
All challenges