How to reverse a string in Rust

How to reverse a string in Rust

To reverse a string in Rust, you can use the chars method on the String type to get an iterator over the characters in the string, then use the rev method on the iterator to reverse it, and finally collect the reversed characters into a new String using the collect method:

fn reverse(s: &str) -> String {
    s.chars().rev().collect()
}

You can then use the reverse function like this:

let s = "hello";
let reversed = reverse(s);
println!("{} reversed is {}", s, reversed);

This will print "hello reversed is olleh".

The chars method on a String returns an iterator over the characters in the string. This iterator has a number of useful methods, such as rev, which returns an iterator over the characters in the reverse order.

The collect method on an iterator takes elements produced by the iterator and collects them into a number of different data structures. In this case, we're using it to collect the reversed characters into a new String.


  • Date: