Rust Practice Exercises

Reverse a String in Rust

Reverse characters and words correctly, including letters like é.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • 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.

Key points

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

Runnable Rust example

Rust
Run code →
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"));
}
Get a Run button for this example Result of running the code
tsuR
olléh
productive fast safe

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.

Next: Tuples and Arrays →

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