{

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 character 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 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.