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
.
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.
chars()
function returns an iterator of the chars in the string it is called upon.rev()
function takes the iterator returned by Chars, and creates an iterator that is the reverse of the chars.Collect()
evaluates the iterator it is called on, and converts the iterator into a collection. It turns a char
iterator into a String
.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
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
.
usize
directly. We can however access chars in a Vec
in this way.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
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.