How to Remove first and last characters of a Strings in Rust example

This tutorial explores multiple methods for removing 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 method removes the first and last characters by creating a string slice range starting from index 1 to string.length - 1. Syntax is 1..string.lengh-1

    fn main() {
      
        let name = "Welcome";
        if name.len() >= 2 {
          let result = &name[1..name.len() - 1];
          println!("{}", result);
            } else {
            println!("String length is less than 2 characters");
        }
    }

    Output:

    elcom
  • using split_at with index:

    This approach splits the string using split_at function with the index string.len() - 1, then further splits the first string with index 1 and prints it.

    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
  • Using String.chars iterator

    This method utilizes the String.chars iterator to iterate over each character, skipping the first character and taking the remaining characters excluding the last one, and then collecting them into a new string.

    fn main() {
        let name = "Welcome";
        let name: String = name.chars().skip(1).take(name.len() - 2).collect();
        println!("{}", name);
    }
  • Using String’s Built-in Methods

    This approach involves creating a mutable string, allowing modification, then using the remove method to delete the first character and the pop method to remove the last character.

    The original string variable is modified and retun the result.

    fn main() {
        let mut name = String::from("Welcome");
        name.remove(0);
        name.pop();
        println!("{}", name);
    }

Summary

This tutorial presents multiple methods for removing the first and last characters of a string in Rust, offering flexibility and versatility to developers based on their use.