How to Reverse a String in Rust

Created
Modified

Using rev Function

The str::rev() function reverses an iterator’s direction.

See the following example:

fn main() {
  let mut s = "Hello";
  println!("{}", s.chars().rev().collect::<String>());

  s = "a̐éö";
  println!("{}", s.chars().rev().collect::<String>());
}
olleH
̈óe̐a

Using unicode-segmentation Crate

Installation

This crate is fully compatible with Cargo. Just add it to your Cargo.toml:

[dependencies]
unicode-segmentation = "1"

unicode-segmentation Usage

use unicode_segmentation::UnicodeSegmentation;

fn main() {
  let mut s = "Hello";
  println!("{}", s.graphemes(true).rev().collect::<String>());

  s = "a̐éö";
  println!("{}", s.graphemes(true).rev().collect::<String>());
}
olleH
öéa̐

Related Tags