Iterate over characters in a Rust string using the .chars() method to handle UTF-8 encoding correctly.
Use the .chars() method on a String to iterate over its characters, which handles UTF-8 encoding correctly.
let text = "Hello, δΈη!";
for c in text.chars() {
println!("Character: {}", c);
}
This loop prints each character individually, including multi-byte Unicode characters like "δΈ" and "η".
In Rust, strings are made of bytes, but characters can be larger than one byte. The .chars() method breaks the string into individual, readable characters so you can process them one by one. Think of it like reading a sentence word by word instead of letter by letter, ensuring you don't cut a word in half.