Accessing the char at a byte index

From the docs:

Indexing is intended to be a constant-time operation, but UTF-8 encoding does not allow us to do this. Furthermore, it's not clear what sort of thing the index should return: a byte, a codepoint, or a grapheme cluster. The bytes and chars methods return iterators over the first two, respectively.

So you need to iterate through the string to find the character you want. Something like this:

my_string.chars().nth(i).unwrap()

my_string.bytes().nth(i).unwrap()
3 Likes