rustHow do I reverse a string in Rust?
Reversing a string in Rust is a simple task that can be accomplished with the .chars().rev()
method. This method returns an iterator that yields the characters of the string in reverse order.
let s = "Hello World";
let reversed = s.chars().rev().collect::<String>();
println!("{}", reversed);
Output example
dlroW olleH
The code above consists of the following parts:
-
let s = "Hello World";
- This line declares a variables
and assigns it the value of the string"Hello World"
. -
let reversed = s.chars().rev().collect::<String>();
- This line uses the.chars()
method to convert the strings
into an iterator of characters, then uses the.rev()
method to reverse the order of the characters, and finally uses the.collect()
method to collect the reversed characters into a new string. -
println!("{}", reversed);
- This line prints the reversed string to the console.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to match whitespace with a regex in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to parse JSON string in Rust?
- How to use a HashBrown with a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to replace all matches using Rust regex?
See more codes...