How to Reverse a String in Rust

Authors

Reversing a string in Rust is a simple task that can be accomplished in various ways.

Here are three possible methods:

Using a loop

One way to reverse a string in Rust is to use a loop.

This method works by iterating through the characters of the string from the end to the beginning and appending each character to a new string.

fn reverse_string(s: &str) -> String {
    let mut reversed = String::new();
    for c in s.chars().rev() {
        reversed.push(c);
    }
    reversed
}

In this method, we create a new empty string called reversed and iterate through the characters of the input string s in reverse order using the .rev() method.

We then append each character to the reversed string using the .push() method. Finally, we return the reversed string.

Using the built-in chars() and collect() methods

Another way to reverse a string in Rust is to use the built-in chars() and collect() methods.

This method works by converting the string to a collection of characters, reversing the collection, and converting it back to a string.

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

In this method, we use the chars() method to convert the string to a collection of characters, the rev() method to reverse the collection, and the collect() method to convert the collection back to a string.

This method is more concise than the loop method.

Using the chars() and fold() methods

A third way to reverse a string in Rust is to use the chars() method and the fold() method.

This method works by iterating through the characters of the string from the beginning to the end and prepending each character to a new string.

fn reverse_string(s: &str) -> String {
    s.chars().fold(String::new(), |mut rev, c| {
        rev.insert(0, c);
        rev
    })
}

In this method, we use the chars() method to iterate through the characters of the input string s.

We then use the fold() method to accumulate the characters into a new string called rev.

For each character c, we use the .insert() method to insert it at the beginning of the rev string.

Finally, we return the rev string.

Summary

These are three ways to reverse a string in Rust.

You can choose the method that you find most readable and efficient for your use case.

TrackingJoy