How do I get the value of a character at position n in a string? For example, if I had the string "Hello, world!", how would I get the value of the first character?
CodePudding user response:
It's simple as s.chars().nth(n)
.
However, beware that like said in the docs:
It’s important to remember that
char
represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead.
See How to iterate over Unicode grapheme clusters in Rust?.
For the first character specifically, you can use s.chars().next()
.
If your string is ASCII-only, you can use as_bytes()
: s.as_bytes()[n]
. But I would not recommend that, as this is not future-proof (though this is faster, O(1) vs O(n)).