How to Remove first and last characters of a Strings in Rust example
This tutorial explains multiple ways to remove the first and last characters of a string in Rust.
How to remove the first and last characters of a String
There are multiple ways we can do it.
- String slice range
This example removes the first and last characters and returns the string.
Using a range of a string length starting from
1..string.length-1
fn main() {
let name = "Welcome";
let result = &name[1..name.len() - 1];
println!("{}", result);
}
Output:
elcom
-
using split_at with index:
-
String.split_at functions is split with string.len()-1
-
Next, takes the first string and split it with index=1
-
Print the string with index=1 position
fn main() {
let name = "Welcome";
let name = name.split_at(name.len() - 1);
let name = name.0.split_at(1);
println!("{}", name.1);
}
Output:
elcom