rustHow do I iterate over a string in Rust?
Iterating over a string in Rust is done using the chars() method. This method returns an iterator over the characters of a string.
Example code
let my_string = "Hello World!";
for c in my_string.chars() {
println!("{}", c);
}
Output example
H
e
l
l
o
W
o
r
l
d
!
Code explanation
let my_string = "Hello World!";: This line declares a string variable.for c in my_string.chars(): This line starts a for loop that iterates over the characters of the string.println!("{}", c);: This line prints each character of the string.
Helpful links
More of Rust
- How to use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...