Rust Loop Over String CharsUse an iterator to loop over the chars in a string. Learn how to loop over chars in reverse.
Loop over chars. Whenever we need to use strings in Rust, we usually will need to loop over their chars and modify them in some way. Rust provides iterators over strings.
For-in loop. With a for-in loop, we can use an iterator with minimal syntax to loop over a string. We can use the loop to create a new string, or perform other logic.
First example. To begin, we have a simple string that contains the word "abc." We call chars() to get an iterator of all the characters in this string.
For We use a for-in loop directly on the iterator returned by chars. Each time the loop executes, the variable is set to a character.
Rust program that uses chars, for-loop
fn main() { let test = "abc"; // Get chars. let values = test.chars(); // Use for-in loop to print all chars. for c in values { println!("CHARACTER: {}", c) } }
Reverse loop. We can change how the iterator returned by chars() loops over characters. With rev(), for example, we can loop over the chars in reverse order.
Rust program that uses chars, rev function
fn main() { let test = "cat"; // Loop over chars backwards. for c in test.chars().rev() { println!("REV: {}", c) } }
REV: t REV: a REV: c
A review. We cannot directly access the chars in a string, as each char may be a different size. But with iterators, we can loop over and test each char in order.
© 2007-2022 sam allen.
see site info on the changelog.