To get the last N characters of a given string in Rust, you can use the `slice` method with negative indices.
In this example,
str1
with a string value of "Hello World"
.&str1[str1.len() - 5..]
to get the last 5 characters.fn main() {
let str1 = "Hello World";
let last5_chars = &str1[str1.len() - 5..];
println!("Last 5 characters of the string are: {}", last5_chars);
}
Last 5 characters of the string are: World
In this example,
str2
with a string value of "apple"
.&str2[str2.len() - 3..]
to get the last 3 characters.fn main() {
let str2 = "apple";
let last3_chars = &str2[str2.len() - 3..];
println!("Last 3 characters of the string are: {}", last3_chars);
}
Last 3 characters of the string are: ple
In this tutorial, we learned How to get Last N Characters in String in Rust language with well detailed examples.