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 variables
and 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 index1
from the iterator.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to match whitespace with a regex in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to parse JSON string in Rust?
- How to use a HashBrown with a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to replace all matches using Rust regex?
See more codes...