How to remove first and last character of a string in Rust?

Viewed 19159

I'm wondering how I can remove the first and last character of a string in Rust.

Example:

Input:

"Hello World"

Output:

"ello Worl"

4 Answers

You can use the .chars() iterator and ignore the first and last characters:

fn rem_first_and_last(value: &str) -> &str {
    let mut chars = value.chars();
    chars.next();
    chars.next_back();
    chars.as_str()
}

It returns an empty string for zero- or one-sized strings and it will handle multi-byte unicode characters correctly. See it working on the playground.

I did this by using string slices.

fn main() {
    let string: &str = "Hello World";
    let first_last_off: &str = &string[1..string.len() - 1];
    println!("{}", first_last_off);
}

I took all the characters in the string until the end of the string - 1.

…or the trivial solution
also works with Unicode characters:

let mut s = "Hello World".to_string();
s.pop();      // remove last
s.remove(0);  // remove first

You can also use split_at().

let msg = "Hello, world!";
let msg = msg.split_at(msg.len() - 1);
let msg = msg.0.split_at(1);
println!("{}", msg.1);

ello, world

split_at() returns the following: (&str, &str).

Related