How to iterate over a string character by character (by Unicode characters) in Rust?
Hi everyone! I just started learning Rust, and I'm having trouble iterating over a string. In other languages (like Python or C++), I'm used to strings being arrays of characters, and I can simply iterate by index or use a for loop.
But in Rust, it's more complicated. Here's what I tried:
```rust
let s = "Привет, мир!";
for c in s {
println!("{}", c);
}
```
The compiler gives an error: `error[E0277]: the trait bound \`str: Iterator\` is not satisfied`. I understand that `str` is not an iterator, but how do I get each character then?
I also tried accessing by index:
```rust
let s = "Привет";
println!("{}", s[0]); // Error!
```
And again an error: strings in Rust cannot be indexed directly because Unicode characters can take up different numbers of bytes.
In the end, I'm
No answers yet.
Log in to leave an answer