rust iterate over string
You can iterate over the characters in a Rust String
using a for
loop and calling the .chars()
method on the String
. Here's an example:
rust iterate over string
let s = "Hello, world!".to_string(); for c in s.chars() { println!("{}", c); }
This will print each character in the string on a separate line.
You can also use the .bytes()
method to iterate over the bytes in a String
, or the .enumerate()
method to get both the index and the character at each position in the string.
for (i, c) in s.chars().enumerate() { println!("{}: {}", i, c); }
This will print the index and character for each position in the string, like this:
0: H 1: e 2: l 3: l 4: o 5: , 6: 7: w 8: o 9: r 10: l 11: d 12: !
Iterating over a String
like this is useful when you need to perform some action on each character in the string, such as printing it or adding it to some other data structure. It's also a way to access the characters in a String
when you need to process them one at a time, rather than as a single entity.