String Reverse ExampleReverse a string with the chars iterator, the rev function, and the collect function. Understand how iterators work.
This page was last reviewed on Feb 17, 2022.
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.
Detail This function returns an iterator of the chars in the string it is called upon.
Loop, String Chars
Detail This function takes the iterator returned by Chars, and creates an iterator that is the reverse of the chars.
Detail This 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}"); }
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.
Tip In Rust we cannot access chars with a usize directly. We can however access chars in a Vec in this way.
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}"); }
A 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 17, 2022 (edit link).
© 2007-2024 Sam Allen.