In Rust, you can use indexing with the length of the string minus one to get the last character.
In this example,
str
with a value of "Hello World"
.[]
with str
and str.len() - 1
to get the last character.fn main() {
let str = String::from("Hello World");
let last_char = str.chars().nth(str.len() - 1);
match last_char {
Some(c) => println!("Last character of the string is: {}", c),
None => println!("String is empty."),
}
}
Last character of the string is: d
In this example,
str
with a value of "apple"
.[]
with str
and str.len() - 1
to get the last character.fn main() {
let str = String::from("apple");
let last_char = str.chars().nth(str.len() - 1);
match last_char {
Some(c) => println!("Last character of the string is: {}", c),
None => println!("String is empty."),
}
}
Last character of the string is: e
In this tutorial, we learned How to get Last Character in String in Rust language with well detailed examples.