To remove the last N characters of a string in Rust, you can use string's truncate method with the length of the string minus N.
In this example,
str1
with a value of "Hello World"
.fn main() {
let mut str1 = String::from("Hello World");
str1.truncate(str1.len() - 3);
println!("Modified string is: {}", str1);
}
Modified string is: Hello Wo
In this example,
str2
with a value of "apple"
.fn main() {
let mut str2 = String::from("apple");
str2.truncate(str2.len() - 2);
println!("Modified string is: {}", str2);
}
Modified string is: app
In this tutorial, we learned How to Remove last N Characters in a String in Rust language with well detailed examples.