Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

rust

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

Example:

Input:

"Hello World"

Output:

"ello Worl"

like image 419
Henry Avatar asked Jan 31 '21 06:01

Henry


2 Answers

…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
like image 192
Kaplan Avatar answered Oct 05 '22 23:10

Kaplan


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.

like image 44
kmdreko Avatar answered Oct 05 '22 23:10

kmdreko