rustHow do I get a character from a string in Rust by its index?
You can get a character from a string in Rust by its index using the chars() method. This method returns an iterator over the characters of a string.
Example code
let s = "Hello";
let c = s.chars().nth(1);
Output example
Some('e')
Code explanation
let s = "Hello": This declares a string variablesand assigns it the value"Hello".let c = s.chars().nth(1): This uses thechars()method to get an iterator over the characters of the strings. Thenth(1)method is then used to get the character at the index1from the iterator.
Helpful links
More of Rust
- Generator example in Rust
- How to convert a u8 slice to a hex string in Rust?
- How to replace strings using Rust regex?
- How to use a tuple as a key in a Rust HashMap?
- How to use regex lookbehind in Rust?
- How to use regex lookahead in Rust?
- How to make regex case insensitive in Rust?
- How to use regex to match a double quote in Rust?
- How to match whitespace with a regex in Rust?
- How to sort the keys in a Rust HashMap?
See more codes...