In place string reverse in Rust

Did you ever get asked in place string reverse in any programming language in interviews? Many years ago, I was asked 🙂
Now let’s get into it in #RUST programming language. It’s pretty simple to be fair.

Rust
pub fn reverse_string_in_place(value: &mut String) {
    unsafe {
        let bytes = value.as_bytes_mut();

        let mut head = 0;
        let mut tail = bytes.len() - 1;

        while head < tail {
            bytes.swap(head, tail);

            head += 1;
            tail -= 1;
        }
    }
}

The usage would be like;

Rust
use crate::string_functions::reverse_string_in_place;
mod string_functions;

fn main() {

    let mut word = String::from("Hello World");

    reverse_string_in_place(&mut word);
    println!("{}", word);
}

Any as you may expect, the output would be;

dlroW olleH

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top