To reverse a string in Rust, you can use the chars()
iterator to get individual characters, collect them into a vector, and then use into_iter().rev()
to reverse the vector.
In this example,
str1
with a value of "Hello World"
.str1
into an iterator of characters using chars()
.into_iter().rev()
.fn main() {
let str1 = String::from("Hello World");
let reversed_str1: String = str1.chars().collect::<Vec<char>>().into_iter().rev().collect();
println!("Reversed string is: {}", reversed_str1);
}
Reversed string is: dlroW olleH
In this example,
str2
with a value of "apple"
.str2
into an iterator of characters using chars()
.into_iter().rev()
.fn main() {
let str2 = String::from("apple");
let reversed_str2: String = str2.chars().collect::<Vec<char>>().into_iter().rev().collect();
println!("Reversed string is: {}", reversed_str2);
}
Reversed string is: elppa
In this tutorial, we learned How to Reverse a String in Rust language with well detailed examples.