How to get the first character from a string in Rust?
Hi everyone! I recently started learning Rust and encountered what seems like a simple task: I need to get the first character from a string. In Python, I would write `text[0]`, and it works. But in Rust, this approach doesn't work.
Here's my code:
```rust
fn main() {
let greeting = String::from("Привет, мир!");
let first_char = greeting[0];
println!("First character: {}", first_char);
}
```
The compiler gives an error: `the type 'String' cannot be indexed by 'usize'`. I understand that strings in Rust are not just arrays of characters, but UTF-8 encoded byte sequences. But how do I get the first character then? The documentation mentions `.chars()` and `.bytes()`, but I'm confused.
I need exactly the first grapheme representation (character), not a byte. For example, for the string "Привет
No answers yet.
Log in to leave an answer