Reverse string. A program may have a requirement to have a reversed string. The reversed string can be used as a key or have internal purposes in the program.
In Rust, we can use 2 iterators—the chars and rev iterators—to reverse the data in a String. Then collect() can convert the data back into a String.
Example function. In Rust we could use a loop and build up a new string. But a more elegant solution is possible—this solution can be easier to review and ensure it has no bugs.
Note The chars() function returns an iterator of the chars in the string it is called upon.
Next The rev() function takes the iterator returned by Chars, and creates an iterator that is the reverse of the chars.
Then Collect() evaluates the iterator it is called on, and converts the iterator into a collection. It turns a char iterator into a String.
Tip To use collect() we must often specify a type. The compiler is unable to figure out what our desired type is on its own.
fn main() {
let initial = "cat".to_string();
// Get chars from string (Chars iterator returned).// Reverse the chars (Rev iterator returned).// Call Collect to convert Char iterator into String.
let reversed: String = initial.chars().rev().collect();
println!("{reversed}");
}tac
Loop example. It is possible to use a reverse-ordered loop to create the reversed string. But we must first get the chars in a vector from the original string.
Info If you have some need to check each char in a loop, this style of code can be superior to the version with chars and rev.
fn reverse_alternate(initial: &str) -> String {
// Get chars from string.
let chars: Vec<char> = initial.chars().collect();
// Allocate new string.
let mut reversed = String::new();
// Add chars in reverse order, stopping at 0.
let mut index = initial.len() - 1;
loop {
reversed.push(chars[index]);
if index == 0 {
break;
}
index -= 1;
}
reversed
}
fn main() {
let reversed = reverse_alternate("cat");
println!("{reversed}");
}tac
Summary. With Rust we can reverse strings in multiple ways. In some programs, we may prefer an imperative style (with a loop) if we have more complex logic that needs to be performed.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 13, 2025 (edit).