rustHow do I get the last character from a string in Rust?
The easiest way to get the last character from a string in Rust is to use the chars()
method. This method returns an iterator over the characters of a string. To get the last character, we can use the last()
method on the iterator.
let s = "Hello";
let last_char = s.chars().last().unwrap();
println!("The last character of {} is {}", s, last_char);
Output example
The last character of Hello is o
Code explanation
let s = "Hello"
: This line declares a string variables
and assigns it the value"Hello"
.let last_char = s.chars().last().unwrap()
: This line uses thechars()
method to get an iterator over the characters of the strings
. Thelast()
method is then used to get the last character from the iterator. Theunwrap()
method is used to get the character from theOption
type returned bylast()
.println!("The last character of {} is {}", s, last_char)
: This line prints the last character of the strings
.
Helpful links
More of Rust
- How to use groups in a Rust regex?
- How to use a tuple as a key in a Rust HashMap?
- How to get an entry from a HashSet in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to use regex with bytes in Rust?
- How to use non-capturing groups in Rust regex?
- How to get a capture group using Rust regex?
- How to replace all using regex in Rust?
See more codes...