HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
lasthowandremovecharacterruststringfirst

Problem

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

Example:

Input:

"Hello World"

Output:

"ello Worl"

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#65976432, score: 63

Revisions (0)

No revisions yet.