Rust Lang

Rust Reverse String

Reversing a string is a common task that is encountered in various programming scenarios. You will find many tasks such as sanitizing the user input, manipulating the text-based data, and more.

Therefore, learning the various methods and techniques to reverse a string can be valuable. This tutorial explores the different methods and techniques to reverse a string in Rust.

Define a String in Rust

The first step is defining the string value that we wish to reverse. This tutorial does not cover the fundamentals of implementing a string type. You can check the following tutorial to learn more: https://linuxhint.com/rust-string.

To define a string in Rust, we can use the “String::from” function or a string literal. Examples are as follows:

fn main() {
    // Using String::from
    let str1 = String::from("Hello, world!");

    // Using a string literal
    let str2: &str = "Hello, Rust!";

    println!("{}", str1);
    println!("{}", str2);
}

 
This should define two strings as follows:

Hello, world!
Hello, Rust!

 
Let us now focus on the various methods of reversing a string.

Method 1: Using the Built-In Functions

The simplest and most straightforward way to reverse a string in Rust is to use the built-in functions provided by the standard library.

We can use the “chars” method on the string to fetch an iterator over the string characters. We can then use the “rev” method on the iterator to reverse it. Then, we collect the reversed characters using the collect() method.

An example is shown in the following:

fn main() {
    let str = String::from("Hello, Rust!");

    let reversed_string: String = str.chars().rev().collect();

    println!("Reversed string: {}", reversed_string);
}

 
Resulting Output:

Reversed string: !tsuR ,olleH

 

Method 2: Using a Mutable String

Another common method that we can use to reverse a string in Rust is using a mutable string. Consider the following example:

fn reverse_string(s: String) -> String {
    let mut start = 0;
    let mut end = s.len() - 1;

    let mut chars: Vec<char> = s.chars().collect();

    while start < end {
        let temp = chars[start];
        chars[start] = chars[end];
        chars[end] = temp;
        start += 1;
        end -= 1;
    }

    chars.into_iter().collect()
}

fn main() {
    let str = String::from("Hello, Rust!");

    let rev_str = reverse_string(str);

    println!("Reversed string: {}", rev_str);
}

 
We start by defining a custom reverse_string() function. The function starts by accepting a string argument, “s”. Then, we define two mutable variables inside the function – “start” and “end” – which represent the characters’ indices at the beginning and end of the string.

Next, we create a mutable vector of characters (Vec<char>) called “chars” using the chars() method on the input string “s” and collecting the characters into a vector.

In the while loop, we swap the characters at the start and end indices of the chars vector using a temporary variable temp. The loop continues until the start index becomes greater than or equal to the end index, effectively reversing the order of characters in the vector.

Finally, we convert the chars vector back into a string by calling the into_iter() to obtain an iterator over the vector elements and then using collect() to collect the characters into a new string.

Conclusion

This tutorial explored two main ways of reversing a string value in the Rust programming language. First, we explored how to use the built-in Rust functions and using a custom-defined function.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list