How to reverse a string in Rust

Rust-Programs

In this post, We will learn how to reverse a string in Rust in many ways in rust and we will explore different techniques that can be used to reverse a string in Rust

1. How to reverse a string in Rust using split


In this example, we are reversing a string by using the string built-in functions. First, we will split the string into characters and then we will reverse them, and finally, we will collect all the reversed characters into a new string.

To do this logic, we have defined the function reverse_string(). This function accepts the string which we want to reverse as an argument and returns a string which is the reversed string.let us begin with our code examples:

Rust Program to reverse a string


fn main() {
  let str1 = String::from("Hello, world!");
  let str2 = reverse_string(&str1);
  println!("The reverse of string \"{}\" is \"{}\".", str1, str2);
}

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

Output:

To execute the program, we will run it on CLI and we can see the output where “Hello world!” is our original string and
“!dlrow ,olleH” is the output string after reversal.

 rustc -o main main.rs
 ./main
The reverse of "Hello, world!" is "!dlrow ,olleH".

2. Reverse a string in Rust using loop


In this example, we are using another method to reverse a string in Rust. Here we are using the for loop to collect the characters in reverse order. We are iterating over the characters and then pushing them to a new string. This new string will have the reverse of the original string.

Let us understand this with the help of the below code example.

fn main() {
  let str1 = String::from("Hello, world!");
  let str2 = reverse(&str1);
  println!("The reverse of \"{}\" is \"{}\".", str1, str2);
}

pub fn reverse(input: &str) -> String {
    let mut result = String::new();
    for c in input.chars().rev() {
        result.push(c)
    }
    result
}

Output

To execute the program, we will run it on CLI and we can see the output where “Hello world!” is our original string and
“!dlrow ,olleH” is the output string after reversal.

? rustc -o main main.rs
? ./main
The reverse of "Hello, world!" is "!dlrow ,olleH".
?